I/O Error:Cannot open resource, while importing python file from the different directory

StackOverflow https://stackoverflow.com/questions/9818122

  •  25-05-2021
  •  | 
  •  

Question

I'm generating pdf using ReportLab. But when i'm trying to attach image in it, it gives error. If i'm not including image then everything is fine. code runs successfully.

I have the following directory structure.

parentDir\
   main.py
   childDir\
       __init__.py
       first.py
       second.py
       image.jpg

main.py

from childDir.first import methodOfFirst

  #using methodOfFirst

first.py

from second import methodOfSecond

   #using methodOfSecond

second.py

#this second.py file have **ReportLab** Code
   .............
   canvas.drawImage('image.jpg', 0.2*inch, 11.12*inch, width=w*scale, height=h*scale)
   .............

This is the basic skeleton of my code. But when i'm executing, it generates the error:

raise IOError('Cannot open resource "%s"' % name)
 IOError: Cannot open resource "tjsservices.jpg"
   handle_pageBegin args=()

I'm new to python and reportLab so don't know what is the correct way to import such a kind of hierarchy. If all the files are in same directory then it works fine. but when i'm using such a kind of directory structure, it fails.

Just for the simplicity, i had provided this skeleton. Let me know if more code is needed.

So the question is. Why i'm getting this error and how to resolve it? is this the issue of ReportLab (i.e. this kind of importing is not supported by reportLab) or i'm importing files wrong way ? Any help would be greatly appreciated.

Was it helpful?

Solution

All filesystem operations are relative to the current working directory, which is not related to which Python module you're in.

In second.py, you can calculate the path like this:

import os.path
fn = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'image.jpg')
canvas.drawImage(fn, 0.2*inch, 11.12*inch, width=w*scale, height=h*scale)

OTHER TIPS

Your path should be relative to the file you're actually running, not to the modules you're importing.

So, you need to either change your image path to 'childDir/image.jpg', provide the full path(or determine it dynamically), or pass the image path as an argument to imported function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top