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)
本文来自博客园,作者:love_water,转载请注明原文链接:https://www.cnblogs.com/ldsice/articles/18715028/code

浙公网安备 33010602011771号