I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files.
What I essentially want is the ability to do something like the following but using Python and not executing ls.
ls 145592*.jpg
If there is no built-in method for this, I am currently thinking of writing a for loop to iterate through the results of an os.listdir()
and to append all the matching files to a new list.
However, there are a lot of files in that directory and therefore I am hoping there is a more efficient method (or a built-in method).
use os.walk to recursively list your files
Another option:
https://docs.python.org/3/library/fnmatch.html
glob.glob()
is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension andre.match()
, something like so:More flexible, but as you note, less efficient.
You can use subprocess.check_ouput() as
Of course, the string between quotes can be anything you want to execute in the shell, and store the output.
This will give you a list of jpg files with their full path. You can replace
x[0]+"/"+f
withf
for just filenames. You can also replacef.endswith(".jpg")
with whatever string condition you wish.Preliminary code
Solution 1 - use "glob"
Solution 2 - use "os" + "fnmatch"
Variant 2.1 - Lookup in current dir
Variant 2.2 - Lookup recursive
Result
Solution 3 - use "pathlib"
Notes: