In Java you can do File.listFiles() and receive all of the files in a directory. You can then easily recurse through directory trees.
Is there an analogous way to do this in Python?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, there is. The Python way is even better.
There are three possibilities:
1) Like File.listFiles():
Python has the function os.listdir(path). It works like the Java method.
2) pathname pattern expansion with glob:
The module glob contains functions to list files on the file system using Unix shell like pattern, e.g.
files = glob.glob('/usr/joe/*.gif')3) File Traversal with walk:
Really nice is the os.walk function of Python.
The walk method returns a generation function that recursively list all directories and files below a given starting path.
An Example:
import os from os.path import join for root, dirs, files in os.walk('/usr'): print 'Current directory', root print 'Sub directories', dirs print 'Files', filesYou can even on the fly remove directories from ‘dirs’ to avoid walking to that dir: if ‘joe’ in dirs: dirs.remove(‘joe’) to avoid walking into directories called ‘joe’.
listdir and walk are documented here. glob is documented here.