[英]Is possible to store a pickle file inside a python module?
I'm building a python module and I need to store a pickle file for making the module works offline.我正在构建一个 python 模块,我需要存储一个泡菜文件以使模块脱机工作。
My module has the following structure我的模块具有以下结构
In the file "macinfo.py" I use the open() function as follow, for example, to get all companies stored:例如,在“macinfo.py”文件中,我使用如下的 open() function 来存储所有公司:
def all_companies() -> List[Company]:
"""
Get all companies stored in the pickle file.
:return: A list of Company instances
"""
return pickle.load(open("data/companies.pickle", "rb"))
When I try to call the function当我尝试调用 function
all_companies()
inside the file named "macinfo.py" it works but when I call the same function inside "test.py" it raises, obviously, the exception:在名为“macinfo.py”的文件中它可以工作,但是当我在“test.py”中调用相同的 function 时,它显然会引发异常:
FileNotFoundError: [Errno 2] No such file or directory: 'data/companies.pickle'
How can I avoid this?我怎样才能避免这种情况?
EDIT: I tried also to use os.path.abspath()
but the same exception is raised.编辑:我也尝试使用
os.path.abspath()
但引发了相同的异常。
I found a solution by using the special variable __file__
.我通过使用特殊变量
__file__
找到了解决方案。
In the file "macinfo.py" I use the following code to determinate where "companies.pickle" is stored在文件“macinfo.py”中,我使用以下代码来确定“companies.pickle”的存储位置
path_1 = "/".join(str(__file__).split("\\")[0:-1])
path_2 = "/data/companies.pickle"
full_path = path_1 + path_2 if path_1 else "data/companies.pickle"
Then I use full_path
as follow然后我使用
full_path
如下
def all_companies() -> List[Company]:
"""
Get all companies stored in the pickle file.
:return: A list of Company instances
"""
return pickle.load(open(full_path, "rb"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.