2016-11-14 7 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

あなたの変数は実際にはファイルハンドルです。 '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 
関連する問題