用python写一个Windows定期清理临时文件和回收站的脚本
时间: 2023-02-17 11:12:18 浏览: 91
可以使用Python的os模块和shutil模块来实现定期清理临时文件和回收站的脚本。
示例代码如下:
```python
import os
import shutil
import time
# 设置清理间隔时间(以秒为单位)
interval = 86400 # 每24小时执行一次
while True:
# 清理临时文件夹
temp_folder = os.environ['TEMP']
for file in os.listdir(temp_folder):
file_path = os.path.join(temp_folder, file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(e)
# 清理回收站
recycle_bin = os.path.join(os.environ['SystemDrive'], '$Recycle.Bin')
for file in os.listdir(recycle_bin):
file_path = os.path.join(recycle_bin, file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(e)
# 等待一段时间后再次执行
time.sleep(interval)
```
这个脚本会循环清理系统临时文件夹和回收站中的文件,每隔24小时执行一次。
注意:这个脚本需要管理员权限才能运行。