簡體   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