Should glob.glob(...) be preferred over os.listdir(...) or the other way around?
11,272
Solution 1
Both are fine. Also consider os.path.walk
if you actually want to do something with that list (rather then building the list for its own sake).
Solution 2
I'd personally go with glob.glob
, as it's clearer.
However, as it's a wrapper around listdir
, they both get the job done.
Related videos on Youtube
Author by
RubenGeert
Updated on September 16, 2022Comments
-
RubenGeert over 1 year
If I'd like to create a list of all .xls files, I usually use
rdir=r"d:\temp" flist=[os.path.join(rdir,fil) for fil in os.listdir(rdir) if fil.endswith(".xls")] print flist
However, I recently saw an alternative to this, which is
rdir=r"d:\temp" import glob flist=glob.glob(os.path.join(rdir,"*.xls")) print flist
Which of these two methods is to be preferred and why? Or are they considered equally (un)sound?
-
poppie almost 7 yearsfor python 3 it's os.walk