要批量解除Python代码文件中的注释,你可以使用正则表达式和文件操作。以下是一个简单的Python脚本示例,用于读取指定文件夹中的所有`.py`文件,去除其中的单行注释(以``开头),并将结果保存到另一个文件夹中,同时生成操作日志。
import os
import re
def remove_comments(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
with open(file_path, 'w') as file:
for line in lines:
使用正则表达式匹配单行注释
if not re.match(r'^\s*', line):
file.write(line)
def batch_remove_comments(source_folder, target_folder):
if not os.path.exists(target_folder):
os.makedirs(target_folder)
log_file = os.path.join(target_folder, 'CleanNoteLog.txt')
with open(log_file, 'w') as log:
for root, dirs, files in os.walk(source_folder):
for file in files:
if file.endswith('.py'):
source_file = os.path.join(root, file)
target_file = os.path.join(target_folder, file)
try:
remove_comments(source_file)
log.write(f'Processed file: {source_file}\n')
except Exception as e:
log.write(f'Error processing file {source_file}: {e}\n')
调用函数处理指定文件夹中的.py文件
source_folder = 'path/to/source/folder'
target_folder = 'path/to/target/folder'
batch_remove_comments(source_folder, target_folder)
将上述代码保存为一个`.py`文件,例如`remove_comments.py`,并确保将`source_folder`和`target_folder`变量设置为正确的源文件夹和目标文件夹路径。然后运行该脚本,它将遍历源文件夹中的所有`.py`文件,去除注释,并将处理后的文件保存到目标文件夹中,同时记录操作日志到`CleanNoteLog.txt`文件中。
请注意,这个脚本只处理单行注释,并且会忽略空行和以``字符开头的行。如果你需要处理多行注释或其他特殊情况,你可能需要调整正则表达式和处理逻辑。