List Files in Directory Using Wildcards With Python
Let’s say you are trying to retrieve the names of a bunch of files in a given directory that match a specific pattern. You can do this pretty easily at the command line using a command such as the following in Windows.
dir *.txt
Or something like this in Linux:
ls *.txt
But if you want to do this programmatically with Python, you have to do it a little differently. Fortunately, this is very easy using a library that is built into Python (at least in later versions) called glob. It does the wildcard functionality for you. Below is a simple code sample on how you can do this.
import glob fileNames = glob.glob("C:\\Temp\\*.txt") print fileNames
This would give you an output such as the following:
['C:\\Temp\\File1.txt', 'C:\\Temp\\File2.txt', 'C:\\Temp\\File3.txt']