【问题标题】:How to print the subdirectory name using python如何使用python打印子目录名称
【发布时间】:2017-09-28 11:36:06
【问题描述】:

我的代码扫描了“Monitors”文件夹下的目录和子目录,但不知何故我未能打印出子目录名称。

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 中的变量,但以错误结束。

【问题讨论】:

  • 除非io.txtio2.txt 直接存在于E:\Logs\Monitors 中,否则您实际上无法获得该输出。你永远不会从Dell 生成文件。
  • @MartijnPieters 那么有没有其他方法可以用路径名列出目录及其子目录中的所有文件?

标签: python list os.walk


【解决方案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 是该位置的目录和文件名列表。只需对文件名使用循环来处理每个文件名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多