2012-03-22 35 views
2

我正在使用ReportLab生成pdf。但是当我试图在其中附加图像时,它会给出错误。如果我不包括图片,那么一切都很好。代码成功运行。I/O错误:无法打开资源,同时从不同目录导入python文件

我有以下目录结构。

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) 
    ............. 

这是我的代码的基本骨架。但是,当我执行,它会产生错误:

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

我是新来的Python和ReportLab的所以不知道什么是进口这样一种层次结构的正确途径。如果所有文件都在同一个目录中,那么它工作正常。但是当我使用这种目录结构时,它失败了。

只是为了简单起见,我提供了这个骨架。让我知道是否需要更多的代码。

所以问题是。为什么我得到这个错误以及如何解决它?这是ReportLab的问题(即reportLab不支持这种导入)或者我错误地导入文件? 任何帮助将不胜感激。

回答

4

所有的文件系统操作是相对于current working directory,这是不相关的你在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) 
+0

这样一个准确的答案非常感谢你。 – 2012-03-22 10:38:36

2

你的路径应该与你正在运行的文件相关,而不是你正在导入的模块。

所以,你需要更改你的图像路径为“childDir/image.jpg的”,提供完整的路径(或动态地确定它),或者通过图像路径作为参数导入函数。

+0

它帮助我了解了实际的概念。 +1为您的答案的轻松。非常感谢。 – 2012-03-22 10:40:13

相关问题