Python – find files in directory with extension

The glob module finds all the pathnames matching a specific pattern according to the rules used by the Unix Shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.


To list all files ending with *.txt in /home/guest directory:

>>> import glob
>>> glob.glob("/home/guest/*.txt")

[‘/home/guest/syslog.txt’, ‘/home/guest/mysql.txt’, ‘/home/guest/topics.txt’, ‘/home/guest/bus.txt’]

Similarly you can try others.

As mentioned above No tilde expansion will work, so following example will return empty list.

>>> glob.glob("~/guest/*.txt")


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s