Reputation: 31548
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
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
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
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 thetry
clause. [2] Exceptions in theelse
clause are not handled by the precedingexcept
clauses.
Seems clear.
Upvotes: 1
Reputation: 40224
The else
part of try
is executed if there were no exceptions raised.
Upvotes: 0
Reputation: 42040
The else bit is run on success, you are misunderstanding its purpose. See: http://docs.python.org/tutorial/errors.html
Upvotes: 1