How to avoid OSError: Cannot open resource if there is no file, but it'll be one the next time.
trend_ext = r"C:\Users\Angel ONC\Desktop\mapas-delitos-master\Series\Baja California\Ext.png"
trend_fem = r"Series\Baja California\Fem.png"
trend_homculp = r"Series\Baja California\Hcul.png"
trend_homdol = r"Series\Baja California\Hdol.png"
trend_narco = r"Series\Baja California\Nar.png"
Mapa_ext = r"Mapas\Baja California\Ext.png"
Mapa_fem = r"Mapas\Baja California\Fem.png"
Mapa_homculp = r"Mapas\Baja California\Hcul.png"
Mapa_homdol = r"Mapas\Baja California\Hdol.png"
Mapa_narco = r"Mapas\Baja California\Nar.png"
Mapa_robcas = r"Mapas\Baja California\Cas.png"
doc = SimpleDocTemplate("Reportes\Baja California.pdf",pagesize=letter,
rightMargin=72,leftMargin=72,
topMargin=72,bottomMargin=18)
Story=[]
try:
im_Mapa_fem = Image(Mapa_fem, 6*inch, 4*inch)
Story.append(im_Mapa_fem)
im_trend_fem = Image(trend_fem, 6*inch, 4*inch)
Story.append(im_trend_fem)
except:
pass
try:
im_Mapa_ext = Image(Mapa_ext, 6*inch, 4*inch)
Story.append(im_Mapa_ext)
im_trend_ext = Image(trend_ext, 6*inch, 4*inch)
Story.append(im_trend_ext)
except:
pass
try:
im_Mapa_secuestro = Image(Mapa_secuestro, 6*inch, 4*inch)
Story.append(im_Mapa_secuestro)
im_trend_secuestro = Image(trend_secuestro, 6*inch, 4*inch)
Story.append(im_trend_secuestro)
except:
pass
OSError: Cannot open resource "Mapas\\Baja California\\Fem.png"
I need to find a solution when can´t find the file.
Try rewriting the try-execpt block as follows:
#Package for iterating through directories
import glob as glob
directory = r'Mapas\Baja California\*.png'
try:
for files in glob.glob(directory):
im_Mapa_fem = file
im_Mapa_fem = Image(Mapa_fem, 6*inch, 4*inch)
Story.append(im_Mapa_fem)
im_trend_fem = Image(trend_fem, 6*inch, 4*inch)
Story.append(im_trend_fem)
except Exception as e:
print(e)
continue
When continue is used, Python ignores part of a for loop if a condition is satisfied, but proceeds to complete the rest of the loop. However when pass is used, Python ignores the condition and continues to execute the for loop as usual.
So if you want to catch the exception and then move to the next iteration you should use continue and not pass.
This may not work as is since you did not include a MCVE , but this should be the general approach.
Also never use empty except blocks. You should always catch the exception and do something with it for future debugging purposes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.