Mirage
Mirage

Reputation: 31548

Need help with Python delete old dirs script

This is function i am using to delete old dirs in 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"

The problem is everytime i see message removing . .... i also see message

some message for success

I want to know why is else part executed everytime

Upvotes: 0

Views: 112

Answers (5)

amc_552345
amc_552345

Reputation: 31

Try this

    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

Upvotes: 0

Chris Eberle
Chris Eberle

Reputation: 48775

You're using a try/except/else block. If the try block succeeds (nothing is caught with except), then the else block will be executed. This is the normal behavior.

Upvotes: 0

S.Lott
S.Lott

Reputation: 391854

http://docs.python.org/reference/compound_stmts.html#the-try-statement

The optional else clause is executed if and when control flows off the end of the try clause. [2] Exceptions in the else clause are not handled by the preceding except clauses.

Seems clear.

Upvotes: 1

eduffy
eduffy

Reputation: 40224

The else part of try is executed if there were no exceptions raised.

Upvotes: 0

Uku Loskit
Uku Loskit

Reputation: 42040

The else bit is run on success, you are misunderstanding its purpose. See: http://docs.python.org/tutorial/errors.html

Upvotes: 1

Related Questions