2016-11-14 77 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 
相关问题