kevin kevin - 3 months ago 5
Python Question

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?

Answer

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.

Comments