简体   繁体   中英

Read txt files sequentially using Python

I have a problem reading txt files in order. I would like to read the files in the following order:

0.txt
1.txt
2.txt
...
10.txt
11.txt
...
19.txt
20.txt
21.txt
...  

However, the following codes

import os

path = "temp/"
dirs = os.listdir(path)

for filename in sorted(dirs):
    print filename

returns

0.txt
1.txt
2.txt
10.txt
11.txt
...
19.txt
2.txt
20.txt  
...   

Any suggestion?

You are sorting the names literally, instead you can use a key function in order to sort the names based on the integer value of the names:

for filename in sorted(dirs, key=lambda x: int(x.split('.')[0])):
    print filename

Note that if one of your file names doesn't follow the proper format the sorted might raise an exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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