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
以上顺序
请教有什么办法按自然的顺序去历遍?
|      1superrichman      2022-03-05 16:09:13 +08:00 | 
|  |      2geelaw      2022-03-05 16:09:37 +08:00 via iPhone os.walk 没有定义顺序,因此不存在一个特别的顺序,你可以先把所有的结果拿出来,再自行排序。 很可能 os.walk 的实现就是调用文件操作的 API ,通常这个 API 不容许任何复杂的排序逻辑。 例如,Windows Explorer 里面的排序就是 explorer 自己做的。 | 
|  |      3necomancer      2022-03-05 16:16:28 +08:00  2 for f in sorted(files, key=lambda x: int(x.replace('_log.txt', ''))): | 
|  |      4ClericPy      2022-03-05 17:12:52 +08:00 先改成 Path.glob 然后 sorted 的 key 自己定义排序规则 | 
|  |      5shijingshijing      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 。。。 | 
|  |      6SenLief      2022-03-19 00:12:20 +08:00  1 @shijingshijing 可以试试 pathlib 库,Path.glob 是可以排序的,Path.chmod 和 Path.lchmod 可以处理链接。 https://docs.python.org/3/library/pathlib.html | 
|  |      7shijingshijing      2022-03-19 15:47:57 +08:00 @SenLief 谢谢,有时间我试试看。 |