[英]How to print the subdirectory name using python
我的代码扫描“监视器”文件夹下的目录和子目录,但是以某种方式我无法打印子目录名称。
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中使用变量,但以错误结束。
而不是使用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
是该目录的完整路径,而dirnames
和filenames
是该位置中目录和文件filenames
的列表。 只需在文件名上使用循环即可处理每个文件名。
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)
这可能是造成问题的原因,因为您实际上没有加入子目录。
这些可能会有所帮助;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.