0

あなたの助けが必要です。いくつかのファイルを移動する 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))

ありがとうございました!

4

1 に答える 1

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()
于 2013-11-13T08:41:42.857 に答える