簡體   English   中英

Python-用os.walk()遞歸目錄

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

我正在寫一個程序,通過取出某種模式來重命名文件和目錄。 我的重命名功能對於文件來說效果很好,因為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

有人可以提出一種針對所有目錄的解決方案,而不僅僅是一級目錄嗎?

在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

感謝JF Sebastian

這將達到目的( 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

用法:

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

僅列出目錄:

from os.path import isdir

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

還有一個不錯的面向路徑操作和遍歷的OOP樣式庫,稱為py ,它具有非常好的API,我非常喜歡並在所有項目中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM