2

os.walk 历遍文件按顺序的问题...

 2 years ago
source link: https://www.v2ex.com/t/838194
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Python

os.walk 历遍文件按顺序的问题...

  pppguest3962 · 4 小时 58 分钟前 · 302 次点击
for root, dirs, files in os.walk("H:/savelog"):
        for f in files:

文件名以数字开头,想按数字从小到大的顺序去处理,

但默认顺序却是以:

1_log.txt
1001_log.txt
1003_log.txt
1004_log.txt
1117_log.txt
2_log.txt
3_log.txt

请教有什么办法按自然的顺序去历遍?

4 条回复    2022-03-05 17:12:52 +08:00

geelaw

geelaw      4 小时 52 分钟前 via iPhone

os.walk 没有定义顺序,因此不存在一个特别的顺序,你可以先把所有的结果拿出来,再自行排序。

很可能 os.walk 的实现就是调用文件操作的 API ,通常这个 API 不容许任何复杂的排序逻辑。

例如,Windows Explorer 里面的排序就是 explorer 自己做的。

necomancer

necomancer      4 小时 45 分钟前

for f in sorted(files, key=lambda x: int(x.replace('_log.txt', ''))):

ClericPy

ClericPy      3 小时 48 分钟前

先改成 Path.glob

然后 sorted 的 key 自己定义排序规则

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK