python os.walk 排序

编程入门 行业动态 更新时间:2024-10-13 00:33:54

<a href=https://www.elefans.com/category/jswz/34/1770869.html style=python os.walk 排序"/>

python 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():

<

更多推荐

python os.walk 排序

本文发布于:2024-02-12 12:01:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1687710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python   os   walk

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!