如何使用python打印子目录名称

时间:2017-04-30 23:56:04

标签: python list os.walk

我的代码会扫描“监视器”文件夹下的目录和子目录,但不知怎的,我无法打印子目录名称。

Monitors是父目录,Dell是子目录,io是Dell下的文件。

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

我的父目录和代码

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;

输出

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

我想要的输出

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

我尝试在path.join中使用变量,但以错误结束。

2 个答案:

答案 0 :(得分:1)

使用os.walk()遍历树中的所有目录,而不是使用os.listdir()

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

os.walk()上的每次迭代都会为您提供有关一个目录的信息。 dirpath是该目录的完整路径,dirnamesfilenames是该位置的目录和文件名列表。只需在文件名上使用循环来处理每个文件。

答案 1 :(得分:-1)

if os.path.isfile(os.path.join(parent_dir, file)):
str +="File Name: " + os.path.join('E:\\Logs\\Monitors\\', item) + "\n" \

此行似乎绕过了子目录名称。你基本上是在做下面的事情;

If file is file:
  print('E:\Logs\Monitors\' + filename)

这可能是您的问题的原因,因为您实际上并没有加入子目录。

这些可能会有所帮助;

How to get all of the immediate subdirectories in Python

相关问题