Search code examples
pythonpython-3.xglob

Python glob() returning list of paths in an Unexpected/Strange Pattern


I am using glob() to get the relative paths of some files in a list, it returns a list with all the names but in an unexpected pattern rather than in alphabetical order. Here is just a minimal reproducible example, and it also shows the same behavior.

from glob import glob

default = 'database/test/gcide_'
def_paths = glob(default + '*.json')

for i in def_paths:
    print(i)

This is a screenshot from the directory it reads enter image description here

Following is the list of paths it returns

database/test/gcide_w.json
database/test/gcide_n.json
database/test/gcide_x.json
database/test/gcide_q.json
database/test/gcide_a.json
database/test/gcide_v.json
database/test/gcide_c.json
database/test/gcide_d.json
database/test/gcide_o.json
database/test/gcide_r.json
database/test/gcide_j.json
database/test/gcide_s.json
database/test/gcide_z.json
database/test/gcide_k.json
database/test/gcide_b.json
database/test/gcide_u.json
database/test/gcide_f.json
database/test/gcide_e.json
database/test/gcide_p.json
database/test/gcide_g.json
database/test/gcide_h.json
database/test/gcide_i.json
database/test/gcide_l.json
database/test/gcide_m.json
database/test/gcide_y.json
database/test/gcide_t.json

I had recently reinstalled my OS and restored my files from a backup I had made, I doubt if that has anything to do with this problem, because prior to that it worked fine, but I'm not sure.


Solution

  • The first sentence of the glob's documentation says:

    The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order.

    So, there is no order to the results you get from glob. You can sort it in any way you want, as shown in this answer.