【问题标题】:Creating a textual summary at the end of an operation [duplicate]在操作结束时创建文本摘要[重复]
【发布时间】:2013-11-25 18:03:55
【问题描述】:

我需要你的帮助。我创建了一个可以移动一些文件的 Python 2.7 脚本。现在,我想做的是程序末尾的“摘要”,说明移动了哪些文件以及移动到了哪里。但是,此摘要必须以某种方式带有“身份”。让我告诉你我的意思:

- Folder A
    |
    |------- File 1
    |------- File 2
    |------- File 3

-Folder B
    |
    |------- Sub Folder B1
                    |
                    |-------- File 1
                    |-------- File 2
                    |---------File X..

如何在 python 中实现这样的功能?

非常感谢!

编辑:

好的,解决方法如下:

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('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))

谢谢!

【问题讨论】:

标签: python python-2.7


【解决方案1】:

Active State Recipes 上有一个脚本正是这样做的:

#! /usr/bin/env python

# tree.py
#
# Written by Doug Dahms
#
# Prints the tree structure for the path specified on the command line

from os import listdir, sep
from os.path import abspath, basename, isdir
from sys import argv

def tree(dir, padding, print_files=False):
    print padding[:-1] + '+-' + basename(abspath(dir)) + '/'
    padding = padding + ' '
    files = []
    if print_files:
        files = listdir(dir)
    else:
        files = [x for x in listdir(dir) if isdir(dir + sep + x)]
    count = 0
    for file in files:
        count += 1
        print padding + '|'
        path = dir + sep + file
        if isdir(path):
            if count == len(files):
                tree(path, padding + ' ', print_files)
            else:
                tree(path, padding + '|', print_files)
        else:
            print padding + '+-' + file

def usage():
    return '''Usage: %s [-f] <PATH>
Print tree structure of path specified.
Options:
-f      Print files as well as directories
PATH    Path to process''' % basename(argv[0])

def main():
    if len(argv) == 1:
        print usage()
    elif len(argv) == 2:
        # print just directories
        path = argv[1]
        if isdir(path):
            tree(path, ' ')
        else:
            print 'ERROR: \'' + path + '\' is not a directory'
    elif len(argv) == 3 and argv[1] == '-f':
        # print directories and files
        path = argv[2]
        if isdir(path):
            tree(path, ' ', True)
        else:
            print 'ERROR: \'' + path + '\' is not a directory'
    else:
        print usage()

if __name__ == '__main__':
    main()

【讨论】:

  • 这对我的想法来说太过分了 :) 还是谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2019-12-29
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2017-09-26
相关资源
最近更新 更多