os.walk以什么顺序进行迭代? [英] In what order does os.walk iterates iterate?

查看:844
本文介绍了os.walk以什么顺序进行迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心os.walk()给定的文件和目录的顺序.如果我有以下目录,110111222021223303132,输出列表的顺序是什么?

I am concerned about the order of files and directories given by os.walk(). If I have these directories, 1, 10, 11, 12, 2, 20, 21, 22, 3, 30, 31, 32, what is the order of the output list?

按数字排序吗?

1 2 3 10 20 30 11 21 31 12 22 32

还是按ASCII值排序,例如ls给出的内容?

Or sorted by ASCII values, like what is given by ls?

1 10 11 12 2 20 21 22 3 30 31 32

另外,如何获得特定的排序?

Additionally, how can I get a specific sort?

推荐答案

os.walk使用os.listdir.这是os.listdir的文档字符串:

os.walk uses os.listdir. Here is the docstring for os.listdir:

listdir(path)-> list_of_strings

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来确保所需的顺序.

You could, however, use sort to ensure the order you desire.

for root, dirs, files in os.walk(path):
   for dirname in sorted(dirs):
        print(dirname)

(请注意,目录名是字符串而不是整数,因此sorted(dirs)将其按字符串排序-一次即可.

(Note the dirnames are strings not ints, so sorted(dirs) sorts them as strings -- which is desirable for once.

如Alfe和Ciro Santilli所指出的那样,如果要按排序顺序对目录进行递归,则就地修改dirs :

As Alfe and Ciro Santilli point out, if you want the directories to be recursed in sorted order, then modify dirs in-place:

for root, dirs, files in os.walk(path):
   dirs.sort()
   for dirname in dirs:
        print(os.path.join(root, dirname))


您可以自己对此进行测试:


You can test this yourself:

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

如果要按数字顺序列出它们,请使用:

If you wanted to list them in numeric order use:

for dirname in sorted(dirs, key=int):

要对字母数字字符串进行排序,请使用自然排序.

To sort alphanumeric strings, use natural sort.

这篇关于os.walk以什么顺序进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆