2

I use the following command to read the names of all files in a directory in python:

import glob
list_of_files = glob.glob(".../*.txt")

However the elements of the list "list_of_files" seem to have no particular order. at least none that I can tell. i-e were they read in alphabetical order? or in order of last modified time stamp?

slmnkhokhar
  • 87
  • 1
  • 7
  • [check here](http://stackoverflow.com/questions/12093940/reading-files-in-a-particular-order-in-python) if you want them in alphabetical order or similar post retrieval ordering. If you want an ordered traversal of the filesystem I think you will need to implement that yourself. – Andrew Johnson Aug 01 '14 at 00:25

1 Answers1

3

glob uses os.listdir to get filenames to match, and the doc for listdir reads: "Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order."

So you cannot count on an order - even if one appears to exist, it could be platform-specific and unreliable. You will need to sort the list of files yourself based on the criteria you want.

As far as I can see, glob does not contain any code that sorts its results. It's actually a pretty short module in case you want to read it to see what's going on under the hood.

Jason S
  • 13,538
  • 2
  • 37
  • 42