Python - looping over files - order

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.

Tags:

Python