我的代码扫描“监视器”文件夹下的目录和子目录,但不知怎么的,我没有打印子目录名。
显示器是父目录,戴尔是子目录,io是戴尔下的文件。
-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中使用变量,但以错误结尾。
发布于 2017-05-01 00:01:29
与其使用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是该位置的目录和文件名列表。只需在文件名上使用一个循环来处理每个文件名。
https://stackoverflow.com/questions/43712580
复制相似问题