Reputation: 2952
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?
Upvotes: 16
Views: 18752
Reputation: 7180
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.
Upvotes: 6
Reputation: 27880
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).
Upvotes: 9