[英]Need help with Python delete old dirs script
这是 function 我用来删除 python 中的旧目录
def delete_olddirs(days,file_path):
numdays = 60*60*24*days
now = time.time()
for dir in os.listdir(file_path):
r = file_path
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
print "removing ",os.path.join(r,dir)
#shutil.rmtree(os.path.join(r,dir)) #uncomment to use
except Exception,e:
print e
pass
else:
print "some message for success"
问题是每次我看到消息removing. ....
removing. ....
我也看到了消息
some message for success
我想知道为什么每次都执行 else 部分
else 位是在成功上运行的,您误解了它的目的。 请参阅: http://docs.python.org/tutorial/errors.html
http://docs.python.org/reference/compound_stmts.html#the-try-statement
如果以及当控制从
try
子句的末尾流出时,可选的else
子句将被执行。 [2]else
子句中的异常不被前面的except
子句处理。
似乎很清楚。
如果没有引发异常,则执行try
的else
部分。
您正在使用 try/except/else 块。 如果 try 块成功(没有被 except 捕获),那么 else 块将被执行。 这是正常行为。
尝试这个
l=[]
for dir in os.listdir(file_path):
r = file_path
timestamp = os.path.getmtime(os.path.join(r,dir))
if now-numdays > timestamp:
try:
print "removing ",os.path.join(r,dir)
#shutil.rmtree(os.path.join(r,dir)) #uncomment to use
l.append("%s" %os.path.join(r,dir))
except Exception,e:
print e
print "removed the following folders %s" %L
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.