Python Don';我不明白为什么我的文件看起来不可读

Python Don';我不明白为什么我的文件看起来不可读,python,json,file,python-3.7,Python,Json,File,Python 3.7,我正试着给一个文件写一本字典。 当我试图读回它时,它什么也不返回,就好像文件是空的一样。 我看到了文件,里面写了一些东西。 我认为我的写作方式不是最好的,这就是为什么它会产生问题。 我的预期结果是读取文件,取回字典,然后写入。我是这样写的: # this function gets the db_name, creating a text file with the db_name # and creating a empty dictionary with the key that is th

我正试着给一个文件写一本字典。 当我试图读回它时,它什么也不返回,就好像文件是空的一样。 我看到了文件,里面写了一些东西。 我认为我的写作方式不是最好的,这就是为什么它会产生问题。 我的预期结果是读取文件,取回字典,然后写入。我是这样写的:

# 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_文件)
阅读它,但它说它不可读

问题->

返回加载(fp.read(),
io.UnsupportedOperation:不可读
我只想将文本文件转换为字典,以便设置它的键…

尝试用

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

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

你在哪里关闭你正在打开的这些文件?我不…0\u 0,请告诉我这不是问题…它看起来有问题我喜欢的
db\u文件
不应该是全局文件。您可能应该在中定义它。然后该文件将自动关闭。使用
语句来处理文件关闭。通常,您可能会发现您无法从写入后未关闭的文件中读取内容。谢谢大家:)我是python新手,现在将阅读“with”语句,但为什么db_文件不应该是全局的?我在一些方法中使用它,并希望将其传递给其他人。因此,我可以访问完全相同的文件。我得到一个错误:TypeError:expected str、bytes或os.PathLike对象,而不是NoneType,我唯一更改的是路径,即
db\u文件