Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort files in a directory before reading?

I am working with a program that writes output to a csv file based on the order that files are read in from a directory. However with a large number of files with the endings 1,2,3,4,5,6,7,8,9,10,11,12. My program actually reads the files by I guess alphabetical ordering: 1,10,11,12....,2,20,21.....99. The problem is that another program assumes that the ordering is in numerical ordering, and skews the graph results.

The actually file looks like: String.ext.ext2.1.txt, String.ext.ext2.2.txt, and so on...

How can I do this with a python script?

like image 362
Jim Avatar asked Jul 19 '11 07:07

Jim


1 Answers

files = ['String.ext.ext2.1.txt', 'String.ext.ext2.12.txt', 'String.ext.ext2.2.txt']
# files: coming from os.listdir() sorted alphabetically, thus not numerically

sorted_files = sorted(files, key=lambda x: int(x.split('.')[3]))
# returns: ['String.ext.ext2.1.txt', 'String.ext.ext2.2.txt', 'String.ext.ext2.12.txt']
like image 145
eumiro Avatar answered Oct 06 '22 07:10

eumiro