本帖最后由 Mis16800 于 2024-5-11 09:30 编辑
之前的代码
def remove_chinese_code_and_comments_in_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file_name in files:
if file_name.endswith((".java", ".js", ".py")):
file_path = os.path.join(root, file_name)
with open(file_path, "r", encoding="utf-8") as file:
code = file.read()
cleaned_code = remove_chinese_code_and_comments(code)
with open(file_path, "w", encoding="utf-8") as file:
file.write(cleaned_code)
修改后的代码
def remove_chinese_code_and_comments_in_folder(folder_path):
for root, dirs, files in os.walk(folder_path):
for file_name in files:
if file_name.endswith((".java", ".js", ".py")):
file_path = os.path.join(root, file_name)
with open(file_path, "r", encoding="utf-8") as file:
code = file.read()
cleaned_code = remove_chinese_code_and_comments(code)
file.seek(0) # 将文件指针移动到文件的开头
file.truncate() #则会清空文件内容(从文件指针位置开始)
file.write(cleaned_code)
|