How to get files in a directory, including all subdirectories

Viewed 107324

I'm trying to get a list of all log files (.log) in directory, including all subdirectories.

7 Answers
import os
import os.path

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".log")]:
        print os.path.join(dirpath, filename)

You can also use the glob module along with os.walk.

import os
from glob import glob

files = []
start_dir = os.getcwd()
pattern   = "*.log"

for dir,_,_ in os.walk(start_dir):
    files.extend(glob(os.path.join(dir,pattern))) 

A single line solution using only (nested) list comprehension:

import os

path_list = [os.path.join(dirpath,filename) for dirpath, _, filenames in os.walk('.') for filename in filenames if filename.endswith('.log')]

If You want to list in current directory, You can use something like:

import os

for e in os.walk(os.getcwd()):
    print e

Just change the

os.getcwd()

to other path to get results there.

Using standard library's pathlib:

from pathlib import Path

working_dir = Path()
for path in working_dir.glob("**/*.log"):
    print(path)
    # OR if you need absolute paths
    print(path.absolute())
    # OR if you need only filenames without extension for further parsing
    print(path.stem)
Related