0
我正在尝试将文件读入字典,以便关键字是单词,值是该单词的出现次数。我有一些应该工作,但是当我运行它,它给了我一个使用python将文件读入字典时出现错误值错误
ValueError: I/O operation on closed file.
这就是我现在所拥有的:
try:
f = open('fileText.txt', 'r+')
except:
f = open('fileText.txt', 'a')
def read_dictionary(fileName):
dict_word = {} #### creates empty dictionary
file = f.read()
file = file.replace('\n', ' ').rstrip()
words = file.split(' ')
f.close()
for x in words:
if x not in result:
dict_word[x] = 1
else:
dict_word[x] += 1
print(dict_word)
print read_dictionary(f)
你的名为'fileName'的变量实际上是文件句柄。名为'file'的变量是文件的文本内容。至少,如果你的名字描述了分配给他们的东西,那么它将更容易推断问题出在哪里。 – jonrsharpe