Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - looping over files - order

Tags:

python

Does anyone know how Python arranges files when looping over them? I need to loop over some files in a folder in a fixed order (preferably alphanumerically according to the filenames), but Python seems to loop over them in a rather random order. So far I am using this code:

filelist = glob.glob(os.path.join(path, 'FV/*.txt'))
for infile in filelist: 
  #do some fancy stuff
  print str(infile)

and the filenames are printed in an order not really obvious to me.

Is there any simple way to predefine a certain order for that loop? Thanks!

like image 342
lu_siyah Avatar asked Apr 22 '13 13:04

lu_siyah


1 Answers

As far as I can see in the docs, glob.glob() has no defined order. Given this, the easiest way to be sure is to sort the list returned to you:

filelist = glob.glob(os.path.join(path, 'FV/*.txt'))
for infile in sorted(filelist): 
  #do some fancy stuff
  print str(infile)

This will just sort as strings - which gives the simple fixed order you were looking for. If you need a specific order, then sorted() takes key as a keyword argument, which is a function that gives sort order. See the documentation (linked previously) for more.

like image 176
Gareth Latty Avatar answered Nov 02 '22 07:11

Gareth Latty