How is Python's glob.glob ordered? How is Python's glob.glob ordered? python python

How is Python's glob.glob ordered?


Order is arbitrary, but you can sort them yourself

If you want sorted by name:

sorted(glob.glob('*.png'))

sorted by modification time:

import ossorted(glob.glob('*.png'), key=os.path.getmtime)

sorted by size:

import ossorted(glob.glob('*.png'), key=os.path.getsize)

etc.


It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using ls -U. (At least on my machine this produces the same order as listing glob matches).


By checking the source code of glob.glob you see that it internally calls os.listdir, described here:

http://docs.python.org/library/os.html?highlight=os.listdir#os.listdir

Key sentence: os.listdir(path)Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Arbitrary order. :)