需要Python删除旧dirs脚本的帮助

问题描述

|| 这是我用来删除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\"
问题是每次我看到消息“ 1”时,我也看到消息
some message for success
我想知道为什么每次都执行其他部分     

解决方法

http://docs.python.org/reference/compound_stmts.html#the-try-statement   执行可选的
else
子句   控制何时以及何时结束   
try
子句的[2]中的例外   
else
子句不由   前面的“ 6”子句。 似乎很清楚。     ,否则,成功就意味着失败,您误解了它的目的。 请参阅:http://docs.python.org/tutorial/errors.html     ,如果没有引发异常,则执行
try
else
部分。     ,您正在使用try / except / else块。如果try块成功(除了没有任何异常),则将执行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