如何在 Python 中按升序从文件中读取和写入值?

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

Read Multiple Files in ascending order File Name 中有一个问题与在 Java 中按升序读取多个文件有关。但是,我陷入无法按升序读取文件的情况。我有一个包含多个文本文件的文件夹,范围从 "0001_FileNameUnique.txt""0272_FileNameUnique.txt"

我能够读取文件并将我需要的值附加到列表中:-

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]

但是,显然写入new_list的值不是升序的,我希望这些值是按升序写入的(以便在for循环中按升序重新读取文件也)。感谢任何帮助。

更新

根据@Finomnis 在接受的答案中的想法,以下解决方案非常有效:-

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)

排序怎么样?

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