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
2009-03-18 21:25:29
+8
A:
import glob, os
for filename in glob.glob(os.path.join(yourPath, "*.tga"))
print(filename)
vartec
2009-03-18 21:25:51
+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
2009-03-18 21:27:56
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
2009-03-18 21:37:15
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
2009-03-18 21:42:04
Sorry, the comment system seems to have cluttered up my newlines, hope you can decypher that =)
Jotham
2009-03-18 21:42:39
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
2009-03-18 21:45:33
Sure,list_of_files = [os.path.join(directory, file) for file in os.listdir(directory) if file.lower().endswith(extension)]
Jotham
2009-03-18 21:48:58
Thanks Jotham, works great :)
Joan Venge
2009-03-18 21:51:27
PIL is Python Imaging Library. It is worth mentioning how exactly do you use it to detect a file type.
J.F. Sebastian
2009-03-18 22:15:23
@J.F.Sebastian: PIL autodetects the file type of opened images; ` from PIL import Image; i = Image.open('somefile'); print i.format `
Joe Koberg
2009-03-19 06:12:09