首页 > 解决方案 > 如何使用 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()

标签: pythoniofile-handling

解决方案


我想所有文件都以 .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)

推荐阅读