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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With