【发布时间】:2021-09-06 22:56:16
【问题描述】:
我正在尝试使用 ast 阅读我的字典(在我的文件中)
import ast
import os
class just_a_class():
def __init__(self, file,):
self.file = file()
self.read_file = open(self.file,'r+')
def read_file(self):
dict = ast.literal_eval(self.read_file.read())
return 'Input: \n\n {}'.format(dict)
the_class = just_a_class("dict.txt")
print(the_class.self.read_file())
错误:
Traceback (most recent call last):
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 13, in <module>
the_class = just_a_class("dict.txt")
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 6, in __init__
self.file = file()
TypeError: 'str' object is not callable
【问题讨论】:
-
self.file = file()删除那里的括号,file是str,你不应该调用它 -
而且最好在完成后关闭打开的文件,最好不要给与Python内置冲突的变量命名,即@987654327 @ 这里(语法高亮也有帮助...)
-
我认为错误回溯本身的答案很清楚 - “TypeError: 'str' object is not callable”,第 6 行。您正在尝试将字符串(文件)作为函数调用(文件())。正如@Altareos 所述,您需要将其替换为 self.file = file
-
次要旁注:您不希望在此处使用模式
"r+"。您从文件中读取,从不写入,因此打开文件进行读取和写入是一种浪费,并且存在行为不当的风险,因为以读取它为目的而打开的文件现在也可能被意外写入。
标签: python python-3.x dictionary typeerror abstract-syntax-tree