Search code examples
pythonglob

what is the order in which glob.glob reads files? if there is no specific order, can one be specified?


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?


Solution

  • 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.