KendrickTV KendrickTV - 1 month ago 11
Python Question

Looping with error handling

I want to see if a file already exists, and if it does, I want to make a file with an extension and a number. I tried to do this with error handling, but I would have to write out the code 50 times.

Here is the code:

for x in range(50):
po = 1
try:
os.makedirs(acct)
except OSError, e:
try:
os.makedirs(acct + "-"+str(po))
po +=1
except OSError, e:
print "Something is broken! Line 14-15"


If acct = "me" and the files "me" and "me-1" exist, running the program simply prints the line a bunch of times.

Thank you for all your help!

EDIT:
I changed the code to

for po in range(0,5):
try:
os.makedirs(acct)
except OSError, e:
try:
os.makedirs(acct + "-"+str(po))
break
except OSError, E:
print "A weird error popped up. Terminating."
break


For some reason, this creates 2 folders when run.

Answer Source

Figured it out:

The looping at the top created as many as there were. You must specify how many times you want to try and resolve the error.