python os.walk 排序_python – os.walk以什么顺序迭代?

os.walk使用os.listdir。这里是os.listdir的docstring:

listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

06000

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是字符串不是ints,所以排序(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):

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值