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()