djderik djderik - 1 year ago 69
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:

f = open('fileText.txt', 'r+')
f = open('fileText.txt', 'a')
def read_dictionary(fileName):
dict_word = {} #### creates empty dictionary
file =
file = file.replace('\n', ' ').rstrip()
words = file.split(' ')
for x in words:
if x not in result:
dict_word[x] = 1
dict_word[x] += 1
print read_dictionary(f)

Answer Source

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

Try this:

 with open('fileText.txt', 'r') as f:
     file =
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download