Python 按顺序读取文件
我在文件夹中有许多文件,其名称符合约定:Python 按顺序读取文件,python,file-io,Python,File Io,我在文件夹中有许多文件,其名称符合约定: 0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ... 我需要一个接一个地阅读它们,并处理其中的数据。目前,我使用以下命令打开每个文件: import os # This is the path where all the files are stored. folder path = '/home/user/some_folder/' # Open one of the files, for data_f
0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...
我需要一个接一个地阅读它们,并处理其中的数据。目前,我使用以下命令打开每个文件:
import os
# This is the path where all the files are stored.
folder path = '/home/user/some_folder/'
# Open one of the files,
for data_file in os.listdir(folder_path):
...
不幸的是,这并没有按照特定的顺序读取文件(不确定它是如何挑选的),我需要从一个最小的文件名开始读取,然后是一个更大的文件名,依此类推,直到最后一个。一个使用
sorted()
返回新排序列表的简单示例
import os
# This is the path where all the files are stored.
folder_path = 'c:\\'
# Open one of the files,
for data_file in sorted(os.listdir(folder_path)):
print data_file
你可以在这里的
编辑自然排序:
如果您正在寻找自然排序,您可以通过@unutbu看到这一伟大功能,您需要使用自然排序对文件进行排序。您需要小心排序字符串。排序
['1','2','10']
将返回['1','10','2']
@wnnmaw我接受评论,请查看编辑。谢谢@KobiK,效果很好!Pypi natsort适用于我编号的.png
文件。