Pan*_*oro 2 python file python-2.7
我有一个文件列表1.dat,...,N.dat在我想要阅读和分析的目录中.
我做了以下
for f in os.listdir('.'): # read all the files in the directory
if f.endswith('.dat'): # use only the ones with .dat as extansion
print(f)
data1 = np.loadtxt(f)
# some operations on each file
Run Code Online (Sandbox Code Playgroud)
这样,文件以随机顺序拍摄,输出打印:
6.dat
4.dat
8.dat
5.dat
13.dat
10.dat
1.dat
16.dat
20.dat
19.dat
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,我如何强制脚本以有序的方式读取文件?从文件1.dat到N.dat.
您需要获取完整的文件列表,然后按照您想要的顺序对它们进行排序.
files = [f for f in os.listdir('.') if f.endswith('.dat')]
Run Code Online (Sandbox Code Playgroud)
这将为您提供.dat文件列表.您不需要完整for循环,列表理解更快.
排序的技巧是你需要一个能给你正确订单的钥匙.在这种情况下,转换为键的数值:
files.sort(key=lambda f: int(f[:-4]))
Run Code Online (Sandbox Code Playgroud)
这将工作仅当您确定所有的DAT文件具有除最后四个字符数值名称.
现在您可以处理您的清单:
for f in files:
data1 = np.loadtxt(f)
...
Run Code Online (Sandbox Code Playgroud)
对于更复杂的排序算法,我建议使用库natsort.然后你的排序步骤看起来像
from natsort import natsorted
files = natsorted(files)
Run Code Online (Sandbox Code Playgroud)
要么
from natsort import humansorted
files = humansorted(files)
Run Code Online (Sandbox Code Playgroud)
第二个版本是区域设置感知的.
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |