我有一个使用当前路径加载数据的函数,如下所示:open('./filename', 'rb')
。当我从位于同一个包中的模块调用它时,它可以工作,但是当我从另一个包中的模块导入它的包并调用它时,我收到错误,告诉我路径'./filename'
不存在。调用open
会引发错误。造成这种情况的原因是什么,以及如何解决这个问题?
答案 0 :(得分:2)
我不了解最佳做法,但模块的__file__
属性设置为从中加载文件名称的字符串表示形式。因此,您可以这样做:
import os.path
# Get the directory this module is being loaded from
module_directory = os.path.dirname(__file__)
# Get the path to the file we want to open
file_path = os.path.join(module_directory, 'filename')
with open(file_path, 'rb') as f:
# do what you want with the file