How to read multiple text files in a folder with Python? [duplicate]

让人想犯罪 __ 提交于 2021-01-24 18:54:05

问题


I have looked at multiple questions & answers across SO, as well as other platforms pertaining to reading text files in a folder, but unfortunately none seems to work for me at the moment. I have multiple text files in a folder and would like to read them all, and put each text file as a string into a new list new_list.

path = "MyNews_AccidentDataset/News_txt.txt"
all_files = os.listdir(path)

Using this gives me all_files as a list with names of all text 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']
.......

However, when I use open() to read the file,

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)

I get the following error:-

with open(fle) as f:
FileNotFoundError: [Errno 2] No such file or directory: '0106_Car_vehicles_part_falls_on_the_roadway.txt'

although the mentioned file exists in the folder.

Any help in this regard is appreciated.

EDIT Using complete path as in suggested comment by @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()

回答1:


I suppose all files ends with .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)



回答2:


Based on some other comments and answers I got UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 643: ordinal not in range(128). Finally, I could successfully solve the issue by setting the read mode as binary "rb" instead of "r":-

for fle in all_files:
   # open the file and then call .read() to get the text
   with open(os.path.join(path, fle),"rb") as f:
      text = f.read()
      new_list.append(text)


来源:https://stackoverflow.com/questions/57111243/how-to-read-multiple-text-files-in-a-folder-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!