Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should glob.glob(...) be preferred over os.listdir(...) or the other way around?

Tags:

python

list

glob

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?

like image 802
RubenGeert Avatar asked Nov 30 '12 10:11

RubenGeert


People also ask

Is glob faster than OS Listdir?

listdir is quickest of three. And glog. glob is still quicker than os.

Is Scandir faster than Listdir?

scandir() is a directory iteration function like os. listdir(), except that instead of returning a list of bare filenames, it yields DirEntry objects that include file type and stat information along with the name. Using scandir() increases the speed of os.

Does OS Listdir go in order?

Does OS Listdir go in order? By default, the list of files returned by os. listdir() is in arbitrary order.

What is the difference between OS Listdir () and OS walk?

The Python os. listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.


1 Answers

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

like image 110
abbot Avatar answered Sep 20 '22 17:09

abbot