djderik djderik - 24 days ago 7
Python Question

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)

Answer

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()