如何按目录文件名中的数字对文件进行排序?

2022-01-11 00:00:00 python operating-system sorting

问题描述

我有一个目录,其中包含许多按特定顺序命名的文本文件:

I have a directory containing a lot of textfiles named in a specific order:

0.txt
1.txt
2.txt
....
100.txt
101.txt
.....
40000.txt

当我试图检索我正在使用的所有文件的排序列表时:

When im trying to retrieve a sorted list of all the files im using:

for file in sorted(os.listdir(filepath)):
            print(file)

我得到的结果是:

0.txt
1.txt
10.txt
100.txt
1000.txt
10000.txt
10001.txt
10002.txt
10003.txt
10004.txt
.....

这不是我想要的,我想要它按正常的升序排列:

Which is not how i want it, i want it in normal ascending order:

0.txt
1.txt
2.txt
3.txt
4.txt
...

有人知道怎么做吗?


解决方案

可以使用 lambda 表达式

Could use a lambda expression

import os

filelist = os.listdir(path)
filelist = sorted(filelist,key=lambda x: int(os.path.splitext(x)[0]))

for file in filelist:
    print(file)

输出为:

1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
10.txt

相关文章