How do I list all tga files in a directory (non recursive) in Python?
To get a list of all the files and folders in a particular directory in the filesystem, use os. listdir() in legacy versions of Python or os. scandir() in Python 3.
Using Glob() function to find files recursively We can use the function glob. glob() or glob. iglob() directly from glob module to retrieve paths recursively from inside the directories/files and subdirectories/subfiles.
To filter and list the files according to their names, we need to use “fnmatch. fnmatch()” and “os. listdir()” functions with name filtering regex patterns. You may find an example of filtering and listing files according to their names in Python.
If you are doing it based on file extension, you can do something like this:
import os
directory = "C:/"
extension = ".tga"
list_of_files = [file for file in os.listdir(directory) if file.lower().endswith(extension)]
Obviously you can omit the lower() if you can garantee the case of the files. Also there is the excellent path.py (http://pypi.python.org/pypi/path.py) module.
If you do not know the file extension you can use something like PIL (http://www.pythonware.com/products/pil/) to detect the file type by decoding the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With