python 递归地将目录移动到指定的深度

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 递归地将目录移动到指定的深度相关的知识,希望对你有一定的参考价值。

" Reference:  http://stackoverflow.com/questions/7159607 "

import os
import sys


def listdir(path):
    """
    recursively walk directory to specified depth
    :param path: (str) path to list files from
    :yields: (str) filename, including path
    """
    for filename in os.listdir(path):
        yield os.path.join(path, filename)


def walk(path='.', depth=None):
    """
    recursively walk directory to specified depth
    :param path: (str) the base path to start walking from
    :param depth: (None or int) max. recursive depth, None = no limit
    :yields: (str) filename, including path
    """
    if depth and depth == 1:
        for filename in listdir(path):
            yield filename
    else:
        top_pathlen = len(path) + len(os.path.sep)
        for dirpath, dirnames, filenames in os.walk(path):
            dirlevel = dirpath[top_pathlen:].count(os.path.sep)
            if depth and dirlevel >= depth:
                dirnames[:] = []
            else:
                for filename in filenames:
                    yield os.path.join(dirpath, filename)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('path', nargs='?', default='.', help=(
        "path to list files from (defaults to current directory)"))
    parser.add_argument('-d', '--depth', type=int, default=0, help=(
        "maximum level of sub-directories to decend"
        "(defaults to unlimited)."))
    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s ' + __version__)
    args = parser.parse_args()
    for filename in walk(args.path, args.depth):
        print(filename)

以上是关于python 递归地将目录移动到指定的深度的主要内容,如果未能解决你的问题,请参考以下文章

用shell脚本递归遍历某个目录下的所有文件并移动到某个指定的目录中

在PowerShell中递归地将一组文件从一个目录复制到另一个目录

递归地将文件添加到所有目录

如何递归地将目录复制到另一个目录并仅替换未更改的文件?

如果文件不匹配,则递归地将一个目录复制到另一个目录

递归地将python对象图转换为字典