Moi*_*med 2 python io reportlab
我正在使用ReportLab生成pdf.但是,当我试图在其中附加图像时,它会给出错误.如果我不包括图像,那么一切都很好.代码运行成功.
我有以下目录结构.
parentDir\
main.py
childDir\
__init__.py
first.py
second.py
image.jpg
Run Code Online (Sandbox Code Playgroud)
main.py
from childDir.first import methodOfFirst
#using methodOfFirst
Run Code Online (Sandbox Code Playgroud)
first.py
from second import methodOfSecond
#using methodOfSecond
Run Code Online (Sandbox Code Playgroud)
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)
.............
Run Code Online (Sandbox Code Playgroud)
这是我的代码的基本框架.但是当我执行时,它会生成错误:
raise IOError('Cannot open resource "%s"' % name)
IOError: Cannot open resource "tjsservices.jpg"
handle_pageBegin args=()
Run Code Online (Sandbox Code Playgroud)
我是python和reportLab的新手,所以不知道导入这种层次结构的正确方法是什么.如果所有文件都在同一目录中,那么它可以正常工作.但是当我使用这种目录结构时,它会失败.
为了简单起见,我提供了这个骨架.如果需要更多代码,请告诉我.
所以问题是.为什么我收到此错误以及如何解决?这是ReportLab的问题(即reportLab不支持这种导入)或者我导入的文件方式错误?任何帮助将不胜感激.
所有文件系统操作都与当前工作目录相关,这与您所在的Python模块无关.
在second.py中,您可以像这样计算路径:
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)
Run Code Online (Sandbox Code Playgroud)