python os.walk 排序_os.walk按什么顺序迭代?

os.walk使用os.listdir。这是os.listdir的文档字符串:listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.path: path of directory to list

The list is in arbitrary order. It does not include the special

entries '.' and '..' even if they are present in the directory.

(我的重点)。

但是,您可以使用sort来确保所需的顺序。for root, dirs, files in os.walk(path):

for dirname in sorted(dirs):

print(dirname)

(注意,dirnames是字符串而不是int,所以sorted(dirs)将它们排序为字符串——这是需要的。

正如Alfe和Ciro Santilli指出的那样,如果您希望目录按排序顺序递归,那么就在适当的位置修改dirs:for root, dirs, files in os.walk(path):

dirs.sort()

for dirname in dirs:

print(os.path.join(root, dirname))

你可以自己测试一下:import os

os.chdir('/tmp/tmp')

for dirname in '1 10 11 12 2 20 21 22 3 30 31 32'.split():

try:

os.makedirs(dirname)

except OSError: pass

for root, dirs, files in os.walk('.'):

for dirname in sorted(dirs):

print(dirname)

印刷品1

10

11

12

2

20

21

22

3

30

31

32

如果要按数字顺序列出,请使用:for dirname in sorted(dirs, key=int):

要对字母数字字符串进行排序,请使用natural sort。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值