tags:

views:

436

answers:

3

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

+1  A: 

>>> import os
>>> for file in [tga for tga in os.listdir(directory) if tga.endswith(".tga")]:
>>>     print file
Geo
+8  A: 
import glob, os
for filename in glob.glob(os.path.join(yourPath, "*.tga"))
   print(filename)
vartec
+6  A: 

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.

Jotham
I tried this and others, but somehow I got nothing. Tried different formats, on this dir: "C:/Documents and Settings/yunus/My Documents/My Received Files/"Is there any problem with this?
Joan Venge
If you: import os for file in os.listdir("C:/Documents and Settings/yunus/My Documents/My Received Files/"): print filedoes it print anything?
Jotham
Sorry, the comment system seems to have cluttered up my newlines, hope you can decypher that =)
Jotham
Thanks Jotham. It was my fault. I was calling a different function. I also wonder if you can add the path, using your method since it's one liner?
Joan Venge
Sure,list_of_files = [os.path.join(directory, file) for file in os.listdir(directory) if file.lower().endswith(extension)]
Jotham
Thanks Jotham, works great :)
Joan Venge
PIL is Python Imaging Library. It is worth mentioning how exactly do you use it to detect a file type.
J.F. Sebastian
@J.F.Sebastian: PIL autodetects the file type of opened images; ` from PIL import Image; i = Image.open('somefile'); print i.format `
Joe Koberg