tags:

views:

611

answers:

4

I am trying to get list all the log files (.log) in directory and included all subdirectories.

Thanks in advance......

+4  A: 

Checkout Python Recursive Directory Walker. In short os.listdir() and os.walk() are your friends.

cartman
+1  A: 

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.

praavDa
+5  A: 
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)
If you want to search in a different directory from "." you could pass the direcotry as sys.argv[1] and call os.walk(sys.argv[1]).
Additional improvement: Use a generator instead of list comprehension: for filename in (f for f ...)
A: 

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)))
lsc