Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read files sequentially in order [duplicate]

Tags:

python

file-io

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.

like image 281
Gabriel Avatar asked Jan 22 '14 16:01

Gabriel


1 Answers

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

like image 63
Kobi K Avatar answered Sep 28 '22 06:09

Kobi K