【脚本】清空指定文件夹内容

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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值