6

I have a number of files in a folder with names following the convention:

0.1.txt, 0.15.txt, 0.2.txt, 0.25.txt, 0.3.txt, ...

I need to read them one by one and manipulate the data inside them. Currently I open each file with the command:

import os
# This is the path where all the files are stored.
folder path = '/home/user/some_folder/'
# Open one of the files,
for data_file in os.listdir(folder_path):
    ...

Unfortunately this reads the files in no particular order (not sure how it picks them) and I need to read them starting with the one having the minimum number as a filename, then the one with the immediate larger number and so on until the last one.

Gabriel
  • 37,092
  • 64
  • 207
  • 369

1 Answers1

8

A simple example using sorted() that returns a new sorted list.

import os
# This is the path where all the files are stored.
folder_path = 'c:\\'
# Open one of the files,
for data_file in sorted(os.listdir(folder_path)):
    print data_file

You can read more here at the Docs

Edit for natural sorting:

If you are looking for natural sorting you can see this great post by @unutbu

Leniel Maccaferri
  • 97,176
  • 43
  • 357
  • 461
Kobi K
  • 7,239
  • 6
  • 39
  • 83