Skip to content

Instantly share code, notes, and snippets.

@deehzee
Last active February 8, 2017 13:16
Show Gist options
  • Save deehzee/f2ff749f4307ef1810594a2409fd35f8 to your computer and use it in GitHub Desktop.
Save deehzee/f2ff749f4307ef1810594a2409fd35f8 to your computer and use it in GitHub Desktop.
How to walk in a directory in python (Find all files in a directory, or all files in the directory-tree)
# Examples of how to walk through a directory (root)
# File: dir-walk.py
# Debajyoti Nandi
# 2016-11-09
import os
root = "."
# The following lists all files immediately in the root,
# i.e., not in its subdirectory
for fname in next(os.walk(root))[2]:
print(os.path.join(root, fname))
# For python 3x, use
# import pathlib
# pathlib.PurePath(root, fname)
# The following lists all files in the root and its subdirectories
for path, dirs, files in os.walk(root):
for fname in files:
print(os.path.join(path, fname))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment