简体   繁体   English

Python-用os.walk()递归目录

[英]Python - recursive directory hit with os.walk()

I'm writing a program that renames files and directories by taking out a certain pattern. 我正在写一个程序,通过取出某种模式来重命名文件和目录。 My renaming function works well for files since os.walk() targets all files, but no so much with directories 我的重命名功能对于文件来说效果很好,因为os.walk()定位所有文件,但目录却没有

for root, dirs, files in os.walk(path):               # Listing the files
        for i, foldername in enumerate(dirs):
            output = foldername.replace(pattern, "")  # Taking out pattern
            if output != foldername:
                os.rename(                            # Renaming
                    os.path.join(path, foldername),
                    os.path.join(path, output))
            else:
                pass

Could someone suggest a solution to target ALL directories and not only first level ones? 有人可以提出一种针对所有目录的解决方案,而不仅仅是一级目录吗?

Setting topdown=False in os.walk does the trick 在os.walk中设置topdown=False可以解决问题

for root, dirs, files in os.walk(path, topdown=False):  # Listing the files
    for i, name in enumerate(dirs):
        output = name.replace(pattern, "")              # Taking out pattern
        if output != name:
            os.rename(                                  # Renaming
                os.path.join(root, name),
                os.path.join(root, output))
        else:
            pass

Thanks to JF Sebastian ! 感谢JF Sebastian

This will do the trick ( pymillsutils.getFiles() ): 这将达到目的( pymillsutils.getFiles() ):

def getFiles(root, pattern=".*", tests=[isfile], **kwargs):
    """getFiles(root, pattern=".*", tests=[isfile], **kwargs) -> list of files

    Return a list of files in the specified path (root)
    applying the predicates listed in tests returning
    only the files that match the pattern. Some optional
    kwargs can be specified:

    * full=True        (Return full paths)
    * recursive=True   (Recursive mode)
    """

    def test(file, tests):
        for test in tests:
            if not test(file):
                return False
        return True

    full = kwargs.get("full", False)
    recursive = kwargs.get("recursive", False)

    files = []

    for file in os.listdir(root):
        path = os.path.abspath(os.path.join(root, file))
        if os.path.isdir(path):
            if recursive:
                files.extend(getFiles(path, pattern, **kwargs))
        elif test(path, tests) and re.match(pattern, path):
            if full:
                files.append(path)
            else:
                files.append(file)

    return files

Usage: 用法:

getFiles("*.txt", recursive=True)

To list just directories: 仅列出目录:

from os.path import isdir

getFiles("*.*", tests=[isdir], recursive=True)

There is also a nice OOP-style library for path manipulation and traversal called py which has really nice API(s) that I quite like and use in all my projects. 还有一个不错的面向路径操作和遍历的OOP样式库,称为py ,它具有非常好的API,我非常喜欢并在所有项目中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM