2016-11-14 75 views
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) 
+0

你的名爲'fileName'的變量實際上是文件句柄。名爲'file'的變量是文件的文本內容。至少,如果你的名字描述了分配給他們的東西,那麼它將更容易推斷問題出在哪裏。 – jonrsharpe

回答

0

這是因爲文件是在write mode打開。寫入模式爲not readable

試試這個:

with open('fileText.txt', 'r') as f: 
    file = f.read() 
0

使用上下文管理器,以避免手動跟蹤哪些文件是開放的。此外,您還有一些錯誤涉及使用錯誤的變量名稱。我使用了下面的defaultdict來簡化代碼,但它並不是必須的。

from collections import defaultdict 
def read_dict(filename): 
    with open(filename) as f: 
     d = defaultdict(int) 
     words = f.read().split() #splits on both spaces and newlines by default 
     for word in words: 
      d[word] += 1 
     return d 
相關問題