按名称顺序迭代文件,Python

问题描述 投票:1回答:3

我正在像这样迭代一堆文件:

for file in glob('./*.dat'):
            print file

并且输出始终为以下内容:

./SAN0.dat
./SAN4.dat
./SAN1.dat
./SAN2.dat
./SAN3.dat
./SAN5.dat
./SAN6.dat
./SAN7.dat

如何按名称顺序进行迭代(例如,SAN1.dat将是第二个?]

谢谢!

python file iteration
3个回答
6
投票
for file in sorted(glob('./*.dat')):

2
投票
lst = glob('./*.dat')
lst.sort()

0
投票

以下是在python-中按文件名顺序迭代文件的最简单方法->>

import os
for file in sorted(os.listdir(path))
© www.soinside.com 2019 - 2024. All rights reserved.