简体   繁体   中英

Getting Value error when reading file into a dictionary using python

I'm trying to read a file into a dictionary so that the key is the word and the value is the number of occurrences of the word. I have something that should work, but when I run it, it gives me a

ValueError: I/O operation on closed file. 

This is what I have right now:

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)

It is because file was opened in write mode . Write mode is not readable .

Try this:

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

Use a context manager to avoid manually keeping track of which files are open. Additionally, you had some mistakes involving using the wrong variable name. I've used a defaultdict below to simplify the code, but it isn't really necessary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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