2017-04-30 143 views
0

我的代码扫描“Monitors”文件夹下的目录和子目录,但不知何故我无法打印子目录名称。如何使用python打印子目录名称

监视器是父目录,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变量,但有错误结束。

+0

你不能真正得到的是输出,除非'io.txt'和'io2.txt'住在'E:\日志\ Monitors'直接。你永远不会从'Dell'生成文件。 –

+0

@MartijnPieters那么还有什么其他的方式来列出目录中的所有文件及其子目录中的路径名? – Prime

回答

1

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

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

+1

他们甚至从未列出子目录中的文件。 –

相关问题