Python - looping files - order

Does anyone know how Python arranges files when going through them? I need to loop around some files in a folder in a fixed order (preferably in an alphanumeric way according to the file names), but Python seems to iterate over them in 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 file names are printed in a manner not very obvious to me.

Is there an easy way to predefine a specific order for this loop? Thanks!

+8
source share
3 answers

As far as I can see in the docs, glob.glob() does not have a specific order. Given this, the easiest way 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 you the simple fixed order you were looking for. If you need a specific order, then sorted() takes key as the keyword argument, which is a function that sets the sort order. See the documentation (linked earlier) for more information.

+19
source

If you want to iterate over a file only in alphabetical order (and not in alphanumeric format), you can make it case-insensitive by calling sorting as follows:

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

Otherwise, just use the sorted function in the file list.

0
source
 import os for root, dirs, files in os.walk(os.path.join(path, 'FV/'), topdown=True): print root print files.sort(reverse=True) 

This is an alternative .. (given that glob.glob() does not accept parameters for ordering elements, I just presented an alternative to glob.glob() , which is, walk() .. It accepts parameters that may be useful, and I think that downvotes are unfair, but everyone who is entitled to their opinion -.-)

-3
source

All Articles