有没有更好的方法来删除给定子目录中的所有 .py 和 .pyc 文件?

Is there a better way to delete all the .py and .pyc files in a given subdirectory?

我编写了一个脚本来删除给定子目录 "migrations" 中的所有 .py 和 .pyc 文件。最终目标是从我的 django 项目中删除所有迁移文件,因此有多个名为 "migrations" 的子文件夹,我想删除所有 .py 和 .pyc(init[=14 除外=].py) 来自这些文件夹。我在下面编写的脚本有效,但我是 python 的新手,并且认为必须有比所有嵌套循环更好的方法。有什么建议么?这是一个 windows 系统,让我觉得很复杂。

import os
import sys

def delete_py(path, subfolder):
    try:
        if os.path.exists(path):
            for (root, dirs, files) in os.walk(path):
                for dir in dirs:
                    if dir == subfolder:
                        goto = os.path.join(root, dir)
                        for (root, dirs, files) in os.walk(goto):
                            for file in files:
                                if (file.lower().endswith('.py') | 
                                    file.lower().endswith('.pyc')) and 
                                    file != '__init__.py':
                                    print('file: ', file)
                                    # will change to os.remove once finsihed
    except:
        print('Unable to delete files')


if __name__ == "__main__":
    current = os.getcwd()
    delete_py(current, 'migrations')

一个 os.walk 应该可以为您完成大部分工作;您唯一需要的其他循环是遍历每个目录中的 files 。你当然不需要 nested os.walk.

您正在为已经由外部 os.walk() 循环处理的子目录调用 os.walk() 来做双重工作。

您需要测试的是 migrations 是否是当前 root 路径中正在处理的目录中的一个元素:

def delete_py(path, subfolder):
    for root, dirs, files in os.walk(path):
        if subfolder in root.split(os.sep):
            # has subfolder as a directory name in the path, delete .py files here
            for file in files:
                if file == '__init__.py':
                    continue
                if file.endswith(('.py', '.pyc')):
                    os.unlink(os.path.join(root, file))

您也可以使用递归 glob 模式,glob module:

from itertools import chain

def delete_py(path, subfolder):
    pyfiles = glob.iglob(f'**/{subfolder}/**/*.py', recursive=True)
    pycfiles = glob.iglob(f'**/{subfolder}/**/*.pyc', recursive=True)
    for filename in chain(pyfiles, pycfiles):
        if os.path.basename(filename) == '__init__.py':
            continue
        os.unlink(filename)

简单使用

  • 对于linux "find . -name "*.pyc" -删除"
  • 对于 windows: "DEL /S /Q *.pyc"