import os from datetime import datetime, timedelta import time delta = timedelta(days=2) now = datetime.now() delete_time = now - delta path = '/home/tomcat/tomcat-8.5.57-Portal/logs/backup' while True: for dirpath, dirnames, filenames in os.walk(path): for dirname in dirnames: if dirname[-8:].isdigit(): dir_time = datetime.strptime(dirname[-8:], '%Y%m%d') if dir_time < delete_time: for filename in os.listdir(os.path.join(dirpath, dirname)): os.remove(os.path.join(dirpath, dirname, filename)) os.rmdir(os.path.join(dirpath, dirname)) print('clean backup log')怎么结束循环
时间: 2024-02-14 08:13:52 浏览: 83
可以使用 `break` 关键字来结束循环。将 `while True` 改为一个条件语句,当满足条件时就跳出循环,例如:
```
import os
from datetime import datetime, timedelta
delta = timedelta(days=2)
now = datetime.now()
delete_time = now - delta
path = '/home/tomcat/tomcat-8.5.57-Portal/logs/backup'
while condition:
for dirpath, dirnames, filenames in os.walk(path):
for dirname in dirnames:
if dirname[-8:].isdigit():
dir_time = datetime.strptime(dirname[-8:], '%Y%m%d')
if dir_time < delete_time:
for filename in os.listdir(os.path.join(dirpath, dirname)):
os.remove(os.path.join(dirpath, dirname, filename))
os.rmdir(os.path.join(dirpath, dirname))
print('clean backup log')
break # 跳出循环
```
你需要将 `condition` 替换为跳出循环的条件。
阅读全文