0

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.

Prime
  • 3,530
  • 5
  • 28
  • 47
  • You can't actually get that output, unless `io.txt` and `io2.txt` live in `E:\Logs\Monitors` directly. You never produce files from `Dell`. – Martijn Pieters Apr 30 '17 at 23:57
  • @MartijnPieters Then is there any other way to list all the files in the directory and its sub directory with path names? – Prime May 01 '17 at 00:00

1 Answers1

1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343