首页 > 解决方案 > 如何让python读取字典目录中的所有文件?

问题描述

我在一个文件夹中有 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 分配为它正在读取的文件的通配符。

标签: pythondictionary

解决方案


您可以遍历目录中的每个 .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

推荐阅读