Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list all tga files in a directory (non recursive) in Python?

Tags:

python

How do I list all tga files in a directory (non recursive) in Python?

like image 687
Joan Venge Avatar asked Mar 18 '09 21:03

Joan Venge


People also ask

How do I get a list of files in a directory 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.

How do you recursively list files in Python?

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.

How do I filter a file in Python?

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.


1 Answers

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.

like image 150
Jotham Avatar answered Oct 18 '22 17:10

Jotham