How to read & write values from file in ascending order in Python?

There is a question somewhat related in Read Multiple Files in ascending order File Name which pertains to reading multiple files in Ascending order in Java. However, I am stuck in a situation where I am not able to read files in an ascending order. I have a folder with multiple text files ranging from "0001_FileNameUnique.txt" to "0272_FileNameUnique.txt".

I am able to read the files and append the value I need to a list using this:-

path = "/content/drive/My Drive/WindTurbine_AccidentDataset/News_txt.txt"
from pathlib import Path
all_files = [f for f in os.listdir(path) if '.txt' in f] # note: if statement to only get .txt files
new_list = []

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)

new_list = [item.decode(encoding='latin1') for item in new_list]

However, clearly the value written to new_list are not in the ascending order, and I would like the values to be written in an ascending order (so that files re read in ascending order in the for loop too). Any help is appreciated.

UPDATE

Based on the idea by @Finomnis in the accepted answer, the following solution worked like a charm:-

for fle in sorted(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)

Answer

How about sorting?

all_files.sort()
for fle in all_files:
   ...

Leave a Reply

Your email address will not be published. Required fields are marked *