【发布时间】: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不应该是全球性的。您可能应该在withstatement 中定义它。然后文件会自动关闭。 -
使用
with语句来处理文件的关闭。通常,您可能会发现无法从写入后未关闭的文件中读取内容。 -
谢谢你们俩 :) 我是 python 新手,现在将阅读关于 'with' 语句的内容,但为什么 db_file 不应该是全局的?我在几种方法中使用它并想传递它。所以我可以访问完全相同的文件
标签: python json file python-3.7