Python: Handle Missing Files from a Sequence
Question
I have a program that's basically as follows:
for l in range(0,100):
file = open("C:/Twitter/json/user_" + str(l) + ".json", "r")
#do some stuff
file.close()
I am trying to figure out a way to handle the exception that will be thrown if say file 20 is missing, and tell it to continue
. I attempted to use the continue
with a try
statement however, it kept complaining that I wasn't putting it in the loop properly. Any advice would be appreciated.
Basically I tried:
try:
for:
except:
continue
Thanks,
Solution
Something like :
import json
for l in xrange(100):
try:
with open('C:/Twitter/json/user_%d.json' % l, 'r') as f:
data = json.load(f)
#do stuff with obj
except IOError:
pass
edit fixed the code.
OTHER TIPS
you could check file existence and then open it:
import os.path
os.path.exists(file_path)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow