按顺序依次读取文件

Gab*_*iel 5 python file-io

我在文件夹中有许多文件,其名称遵循约定:

0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...
Run Code Online (Sandbox Code Playgroud)

我需要逐个阅读它们并操纵它们内部的数据.目前我用命令打开每个文件:

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):
    ...
Run Code Online (Sandbox Code Playgroud)

不幸的是,它没有按特定的顺序读取文件(不确定它是如何选择它们)而我需要从具有最小数字作为文件名的那个开始读取它们,然后是具有直接较大数字的那个,依此类推直到最后一个.

Kob*_*i K 6

使用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
Run Code Online (Sandbox Code Playgroud)

您可以在文档中阅读更多内容

编辑自然排序:

如果您正在寻找自然分类,您可以看到@unutbu的这篇精彩文章

  • 你需要小心排序字符串.排序```['1','2','10']``将返回```['1','10','2']``` (3认同)