Python: manejar archivos perdidos de una secuencia

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

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 con un try statement however, it kept complaining that I wasn't putting it in the loop properly. Any advice would be appreciated.

Basically I tried:



preguntado el 09 de enero de 11 a las 12:01

2 Respuestas

Algo como:

import json
for l in xrange(100):
        with open('C:/Twitter/json/user_%d.json' % l, 'r') as f:
            data = json.load(f)
            #do stuff with obj
    except IOError:

editar fixed the code.

Respondido el 09 de enero de 11 a las 15:01

Check the modified version, even more "pythonic" :), although the os.path.exists part below is also very valid, mine handles random errors though, like if the file exists but can't be read. - Uno de uno

The problem with using os.path.exists is that the file may be deleted by another process between checking that it is there and opening it. - John La Rooy

Yeah agreed, thats why it's probably safer to go with the try/except. - Uno de uno

you could check file existence and then open it:

import os.path

Respondido el 09 de enero de 11 a las 15:01

Thanks, I used this though since it is a smaller amount of files, but both solutions worked for me. - eWizardII

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.