繁体   English   中英

使用python将文件读入字典时出现Value错误

[英]Getting Value error when reading file into a dictionary using 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)

这是因为文件是在write mode打开的。 写模式not readable

尝试这个:

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

使用上下文管理器可以避免手动跟踪打开了哪些文件。 此外,您在使用错误的变量名时遇到了一些错误。 我在下面使用了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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM