【问题标题】:Don't undestand why my file appears to be unreadable不明白为什么我的文件似乎无法读取
【发布时间】:2020-02-25 22:59:52
【问题描述】:

我正在尝试将字典写入文件。 当我尝试读回它时,它什么也不返回,就好像文件是空的一样。 我看到了文件,里面写了一些东西。 我认为我的写作方式不是最好的,这就是它出现问题的原因。 我的预期结果是读取文件,取回字典,然后写入。我就是这样写的:

# this function gets the db_name, creating a text file with the db_name
# and creating a empty dictionary with the key that is the table_name.

def __createTheDb(self,dirPath, db_name, table_name):
    global db_file
    os.chdir(dirPath)  #gets into the directory
    print(os.getcwd(), "from create the db")
    db_file = open(db_name + ".txt", "w")
    temp_dict = dict.fromkeys(f"{table_name}".split())
    db_file.write(str(temp_dict))
    return db_file

我如何编写文件:

def writeFile(self, db_name, table_name, key, value):
    global db_file, my_json #gets the global variable
    print(type(db_file))
    file = open(db_name,"r").read()
    print(file) #-> the problem is that this prints nothing.

我尝试用json.load(db_file) 阅读它,但它说它不可读。

问题->

return loads(fp.read(),
io.UnsupportedOperation: not readable

我只想将文本文件转换为字典,这样我就可以设置它的关键...

【问题讨论】:

  • 你在哪里关闭你正在打开的这些文件?
  • 我不... 0_0,请告诉我不是问题...
  • 在我看来 db_file 不应该是全球性的。您可能应该在with statement 中定义它。然后文件会自动关闭。
  • 使用with 语句来处理文件的关闭。通常,您可能会发现无法从写入后未关闭的文件中读取内容。
  • 谢谢你们俩 :) 我是 python 新手,现在将阅读关于 'with' 语句的内容,但为什么 db_file 不应该是全局的?我在几种方法中使用它并想传递它。所以我可以访问完全相同的文件

标签: python json file python-3.7


【解决方案1】:

尝试加载它

with open("./path/file.json", "r") as f:
        loadedDic = json.load(f)

如果你加载的文件只是一个字典,那么loadedDic 将等于字典。如果它有一个字典列表,或者一个字典字典等,你需要按照你通常解析列表/字典/等的方式来解析它。

【讨论】:

  • 我得到一个错误:TypeError: expected str, bytes or os.PathLike object, not NoneType,我唯一改变的是路径,应该是db_file
猜你喜欢
  • 2022-12-11
  • 2020-04-12
  • 2018-05-09
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多