Directory-tree listing in Python
This is a way to traverse every file and directory in a directory tree:
import osfor dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git')
You can use
os.listdir(path)
For reference and more os functions look here:
- Python 2 docs: https://docs.python.org/2/library/os.html#os.listdir
- Python 3 docs: https://docs.python.org/3/library/os.html#os.listdir
Here's a helper function I use quite often:
import osdef listdir_fullpath(d): return [os.path.join(d, f) for f in os.listdir(d)]