python - 如何使用 Python 读取文件夹中的多个文本文件?
问题描述
我已经查看了 SO 中的多个问题和答案,以及与读取文件夹中的文本文件有关的其他平台,但不幸的是,目前似乎没有一个对我有用。我在一个文件夹中有多个文本文件,想全部阅读它们,并将每个文本文件作为字符串放入一个新列表中new_list
。
path = "MyNews_AccidentDataset/News_txt.txt"
all_files = os.listdir(path)
使用它会给我all_files
一个包含所有文本文件名称的列表
'0185_Man dies after 100ft turbine fall .txt',
'0131_Deaths_from_Working_with_Wind_Energy - Copy (5) - Copy.txt',
'0001_BENDING_WITH_THE_WIND._Modern_Power_System_N.txt']
.......
但是,当我open()
用来读取文件时,
new_list = []
for fle in all_files:
# open the file and then call .read() to get the text
with open(fle) as f:
text = f.read()
new_list.append(text)
我收到以下错误:-
with open(fle) as f:
FileNotFoundError: [Errno 2] No such file or directory: '0106_Car_vehicles_part_falls_on_the_roadway.txt'
尽管提到的文件存在于文件夹中。
感谢您在这方面的任何帮助。
编辑 使用@bexi建议评论中的完整路径
for fle in all_files:
# open the file and then call .read() to get the text
with open(os.path.join(path, fle)) as f:
text = f.read()
解决方案
我想所有文件都以 .txt 结尾:
new_list = []
for root, dirs, files in os.walk(<path to your folder>):
for file in files:
if file.endswith('.txt')
with open(os.path.join(root, file), 'r') as f:
text = f.read()
new_list.append(text)
推荐阅读
- python - 具有相关名称的反向查找
- c# - 布尔值的 C# 条件不一样
- python - 在 Python 中撤销 celery 任务时如何退出 selenium webdriver
- freemarker - Freemaker 以下已评估为 null 或缺失
- amazon-web-services - [返回结果不正确]AWS Redshift(RedShift)中Join语句中Limit不正确
- ruby-on-rails - ActiveStorage:从 s3 打开已处理的变体
- python - Excel图表中的下标字母
- arrays - 将大数组添加到 c 文件而不重新编译它
- bash - Bash - 连接到 Docker 容器并在 redis-cli 中执行命令
- javascript - 对类组件使用 forwardRef 时,ref 的回调函数不起作用