简体   繁体   English

使用python从文件夹读取文件

[英]Reading files from a folder using python

I am trying to read all files within a directory. 我正在尝试读取目录中的所有文件。

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

This is my code where path is the path of the directory to be read.But it does not print the files in the order of their names. 这是我的代码,其中path是要读取的目录的路径。但是它不会按照文件名的顺序打印文件。 In my case, I have files from 0.txt , 1.txt ,.... to 3590.txt . 就我而言,我的文件从0.txt1.txt ....到3590.txt I want it to print the files in the same order. 我希望它以相同的顺序打印文件。 But rather it starts from 579.txt . 而是从579.txt开始。 How can I fix this? 我怎样才能解决这个问题? I want to do some computation on the files in the same order and so just storing the names in a list and sorting it wont help. 我想以相同的顺序对文件进行一些计算,因此仅将名称存储在列表中并对其进行排序将无济于事。

what about sorting them with a lambda to use the int in the filename: 如何使用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))

As file name structure is like $Number$.txt , so we can sort by Number. 由于文件名结构类似于$Number$.txt ,因此我们可以按Number排序。

Demo : 演示

>>> 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