繁体   English   中英

使用python从文件夹读取文件

[英]Reading files from a folder using python

我正在尝试读取目录中的所有文件。

for root, dirs,files in os.walk(path):
        for j in files:
            print(str(j))

这是我的代码,其中path是要读取的目录的路径。但是它不会按照文件名的顺序打印文件。 就我而言,我的文件从0.txt1.txt ....到3590.txt 我希望它以相同的顺序打印文件。 而是从579.txt开始。 我怎样才能解决这个问题? 我想以相同的顺序对文件进行一些计算,因此仅将名称存储在列表中并对其进行排序将无济于事。

如何使用lambda对它们进行排序以在文件名中使用int呢?

for root, dirs,files in os.walk(path):
    for j in sorted(files, key=lambda key: int(key.replace(".txt", ""))):
        print(str(j))

由于文件名结构类似于$Number$.txt ,因此我们可以按Number排序。

演示

>>> l = ["0.txt", "1.txt", "33.txt", "2.txt", "10.txt", "11.txt"]
>>> sorted([(int(i.replace(".txt", "")), i) for i in l ])
[(0, '0.txt'), (1, '1.txt'), (2, '2.txt'), (10, '10.txt'), (11, '11.txt'), (33, '33.txt')]
>>> [i[1] for i in sorted([(int(i.replace(".txt", "")), i) for i in l ])]
['0.txt', '1.txt', '2.txt', '10.txt', '11.txt', '33.txt']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM