main执行一次,1.txt就会写入一些东西。
原来的想法是覆盖重写,结果却是接着往后面写,检查源代码有点费事,不如在每次程序执行前,先直接清空文件夹!
部分代码:
修改路径就能用。
import os
import shutil
def clear_folder(folder_path):
# 检查文件夹是否存在
if not os.path.exists(folder_path):
print(f"The folder {folder_path} does not exist.")
return
# 删除文件夹中的所有文件和子文件夹
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path) # 删除文件
elif os.path.isdir(file_path):
shutil.rmtree(file_path) # 删除子文件夹
except Exception as e:
print(f"Failed to delete {file_path}. Reason: {e}")
# 调用函数清空指定文件夹
clear_folder('./runs/detect/exp')