Prime
Prime

Reputation: 3625

How to print the subdirectory name using python

My code scans the directories and sub directories under the 'Monitors' folder, but somehow I failed to print the sub directory names.

Monitors is the parent directory and Dell is sub directory and io are the files under Dell.

-Monitors
-------- Cab.txt
--- Dell
-------- io.txt
-------- io2.txt

My parent directory and code

parent_dir = 'E:\Logs\Monitors'

def files(parent_dir):
    for file in os.listdir(parent_dir):
      if os.path.isfile(os.path.join(parent_dir, file)):
        yield file

def created(file_path):
    if os.path.isfile(file_path):
        file_created =  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(file_path)))
        return file_created


len = (item for item in files(parent_dir))
str = ""
for item in len:
    str +="File Name: " + os.path.join('E:\\Logs\\Monitors\\', item) + "\n" \
    + "File Created on: " + created(os.path.join('E:\\Logs\\Monitors\\', item)) + "\n" \
print str;

Output

E:Logs\Monitors\Cab.txt
E:Logs\Monitors\io.txt
E:Logs\Monitors\io2.txt

My Desired Output

E:Logs\Monitors\Cab.txt
E:Logs\Monitors\Dell\io.txt
E:Logs\Monitors\Dell\io2.txt

I tried using the variable in path.join but ended with errors.

Upvotes: 0

Views: 302

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122012

Rather than use os.listdir(), use os.walk() to traverse all directories in a tree:

for dirpath, dirnames, filenames in os.walk(parent_dir):
    for filename in filenames:
        full_path = os.path.join(dirpath, filename)
        print 'File Name: {}\nFile Created on: {}\n'.format(
            full_path, created(full_path))

Each iteration over os.walk() gives you information about one directory. dirpath is the full path to that directory, and dirnames and filenames are lists of directory and filenames in that location. Simply use a loop over the filenames to process each.

Upvotes: 1

Related Questions