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