python - 如何让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 分配为它正在读取的文件的通配符。
解决方案
您可以遍历目录中的每个 .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
推荐阅读
- asp.net - 如何在 ASP.NET MVC 应用程序中正确使用会话?
- python - 将标记化全文传递到 keras 嵌入层的形状错误
- image-processing - 检测并删除照片中的文字
- javascript - Uncaught (in promise) SyntaxError: Unexpected token?
- php - 我想将 mysql 查询转换为 laravel orm 查询
- mysql - MySQL 外键 ON DELETE SET NULL
- java - Google Glass Entreprise Edition 2:无法初始化调试数据
- java - java.lang.NumberFormatException:对于输入字符串:“”
- javascript - Javascript字符串到多维数字数组
- unit-testing - 如何检查一个集合是否包含满足给定条件的 N 个项目?