【问题标题】:Python File Tree + Size and countering number of files and directoriesPython 文件树 + 大小和计数文件和目录的数量
【发布时间】:2019-03-26 12:41:43
【问题描述】:

我目前有这个:

import os

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print("F"+'{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print("D"+'{}{}'.format(subindent, f))
list_files('.')

现在的问题是我需要这样做: 制作一个可执行的 Python 脚本,打印文件树如下:

D 或 F [文件名/目录名] [文件大小/countfilesindirectory]

我只需要添加这个,但我不知道如何: 目录中的文件大小或文件数

我想要改进的是,您也可以在执行请求输入之前自行选择位置

location = input("Location: ")

应递归扫描此位置以查找这些目录并将它们显示在树中。 如果有人可以帮助我,那将非常有用!

提前致谢

~Blackd00r

【问题讨论】:

  • 问题在哪里?你尝试了什么?你的进展如何?
  • import os def tree_printer(root): for root, dirs, files in os.walk(root): for d in dirs: print ("D"+os.path.join(root, d)) for f in files: print ("F"+os.path.join(root, f)) tree_printer('.')

标签: python python-3.x


【解决方案1】:

这个问题的解决方法是:

我为文件和从 0 开始的目录添加了一个计数器。在 forloop 中,我们添加了 dir 的长度,以便计算总数。

print("{} 个文件夹中的{} 个文件".format(filecount, dircount))

import os
def list_files(startpath):
    dircount = 0
    filecount = 0
    for root, dirs, files in os.walk(startpath):
        dircount += len(dirs)
        filecount += len(files)
        level = root.replace(startpath, '').count(os.sep)
        indent = ' ' * 4 * (level)
        print("D"+'{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            path = os.path.join(root, f)
            size = os.stat(path).st_size
            print("F"+'{}{} ({} bytes)'.format(subindent, f, size))
    print("{} files in {} folders".format(filecount, dircount))

list_files('.')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-07
    • 2021-09-09
    • 2015-11-07
    • 2015-06-15
    • 1970-01-01
    • 2020-03-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多