python_防御性编程_删除所有的注释

最近刷博客看到了防御性编程,搞了个自动删除代码注释的脚本,删除前记得备份😂

import os
import re


# 读取一个py文件,删除所有的注释
def remove_comments(file_path):
    # 读取文件
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    # 删除注释
    content = re.sub(r'#.*', '', content)
    # 写入文件
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)


# 递归读取一个文件夹处理所有的py文件
def remove_comments_from_py_files(directory):
    # 递归
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.py'):
                remove_comments(os.path.join(root, file))


# 防御性编程的代码路径
code_dir = r""
remove_comments_from_py_files(code_dir)

posted @ 2025-02-14 11:35  love_water  阅读(12)  评论(0)    收藏  举报