![](/img/trans.png)
[英]How to read all the files of a directory in python and save file data in a dictionary
[英]How to make python read all files in directory for a dictionary?
我在一個文件夾中有 20 個文本文件的集合,我正在嘗試為其創建字典並將字典輸出到文本文件。
我通過輸入文件名創建了一個適用於目錄中單個文件的代碼。 但是,它不允許我一次輸入多個文本文件,如果我單獨運行每個文件,它們只會相互覆蓋。 我嘗試將文件輸入轉換為使用 import os 並從我的 cwd 中讀取,但是我遇到了變量錯誤,我只是不確定我做錯了什么。
fname = input ('Enter File: ')
hand = open(fname)
di = dict()
for lin in hand:
lin = lin.rstrip()
wds = lin.split()
for w in wds:
di[w] = di.get(w,0) + 1
print(di)
largest = -1
theword = None
for k,v in di.items() :
if v > largest :
largest = v
theword = k
print(theword,largest)
f = open("output.txt", "w")
f.write(str(di))
f.close()
我嘗試添加
import os
for filename in os.listdir(os.getcwd()):
fname = ('*.txt')
hand = open(fname)
最重要的是,但我出錯了,因為它沒有識別出我認為將 fname 指定為它正在讀取的文件的通配符。
您可以遍歷目錄中的每個 .txt 文件,並將這些文本文件的內容打印或存儲在字典或變量中。
import os
for filename in os.listdir(os.getcwd()):
name, file_extension = os.path.splitext(filename)
if '.txt' in file_extension:
hand = open(filename)
for line in hand:
print line
如果您使用的是 Python 3.4 或更高版本,則可以使用pathlib.Path()
和collections.Counter()
來非常簡化您的代碼:
from pathlib import Path
from collections import Counter
counter = Counter()
dir = Path('dir')
out_file = Path('output.txt')
for file in dir.glob('*.txt'):
with file.open('r', encoding='utf-8') as f:
for l in f:
counter.update(l.strip().split())
counter.most_common(10)
with out_file.open('w', encoding='utf-8') as f:
f.write(counter)
如果您使用的是 Python 3.5 或更高版本,則該代碼可以更簡單:
from pathlib import Path
from collections import Counter
counter = Counter()
dir = Path('dir')
out_file = Path('output.txt')
for file in dir.glob('*.txt'):
counter.update(file.read_text(encoding='utf-8').split())
counter.most_common(10)
out_file.write_text(counter, encoding='utf-8')
這是示例輸出:
>>> from pathlib import Path
>>> from collections import Counter
>>> counter = Counter()
>>> file = Path('t.txt')
>>> file.is_file()
True
>>> with file.open('r', encoding='utf-8') as f:
... for l in f:
... counter.update(l.strip().split())
...
>>> counter.most_common(5)
[('is', 10), ('better', 8), ('than', 8), ('to', 5), ('the', 5)]
>>>
如果要使用通配符,則需要glob
模塊。 但就您而言,聽起來您只想將所有文件放在一個目錄中,因此:
for filename in os.listdir('.'): # . is cwd
hand = open(filename)
import glob
# a list of all txt file in the current dir
files = glob.glob("*.txt")
# the dictionary that will hold the file names (key) and content (value)
dic = {}
# loop to opend files
for file in files:
with open(file, 'r', encoding='utf-8') as read:
# the key will hold the name the value the content
dic[file] = read.read()
# For each file we will append the name and the content in output.txt
with open("output.txt", "a", encoding = 'utf-8') as output:
output.write(dic[file] + "\n" + read.read() + "\n\n")
也許為時已晚,但我遇到了類似的情況,這就是我使用字典理解來解決的方法
import os
result_dict = {filename: open(filename, 'r').read() for filename in os.listdir(os.getcwd())}
免責聲明:由於我們未使用上下文管理器,因此某些人可能會認為此“笨拙”。 但是,我相信如果在讀取文件時出現問題,則python的垃圾收集器會清理它們。
如果您想進一步了解為什么我們不能在字典理解中使用上下文管理器,請參考以下內容: 為什么此上下文管理器的行為與dict理解不同?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.