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

2022-03-05 16:02:47 +08:00
 pppguest3962
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

以上顺序

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

5086 次点击
所在节点    Python
7 条回复
superrichman
2022-03-05 16:09:13 +08:00
Natural sort 或者 alphanumeric sort

比如
https://github.com/SethMMorton/natsort
geelaw
2022-03-05 16:09:37 +08:00
os.walk 没有定义顺序,因此不存在一个特别的顺序,你可以先把所有的结果拿出来,再自行排序。

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

例如,Windows Explorer 里面的排序就是 explorer 自己做的。
necomancer
2022-03-05 16:16:28 +08:00
for f in sorted(files, key=lambda x: int(x.replace('_log.txt', ''))):
ClericPy
2022-03-05 17:12:52 +08:00
先改成 Path.glob

然后 sorted 的 key 自己定义排序规则
shijingshijing
2022-03-09 11:21:42 +08:00
@geelaw 我有一个问题想请教一下,如果遍历文件夹的时候,碰到那种文件夹里面快捷方式 /链接引用文件夹本身的情况,有什么比较好的最佳实践么?

比如 D:/test/mydir/下面有个 mydir.lnk 是指向 D:/test/mydir/本身的。

我在微软官方网站上找到了一些描述这方面的资料:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-iterate-through-a-directory-tree

中间有一段 Note:
NTFS file systems can contain reparse points in the form of junction points, symbolic links, and hard links. .NET methods such as GetFiles and GetDirectories will not return any subdirectories under a reparse point. This behavior guards against the risk of entering into an infinite loop when two reparse points refer to each other. In general, you should use extreme caution when you deal with reparse points to ensure that you do not unintentionally modify or delete files. If you require precise control over reparse points, use platform invoke or native code to call the appropriate Win32 file system methods directly.

最近做这方面的开发,发现涉及到文件系统的话,要考虑的东西太多了,Permission ,Shared Folder ,Shortcut 。。。
SenLief
2022-03-19 00:12:20 +08:00
@shijingshijing 可以试试 pathlib 库,Path.glob 是可以排序的,Path.chmod 和 Path.lchmod 可以处理链接。
https://docs.python.org/3/library/pathlib.html
shijingshijing
2022-03-19 15:47:57 +08:00
@SenLief 谢谢,有时间我试试看。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/838194

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX