Reputation: 337
I'm building a python module and I need to store a pickle file for making the module works offline.
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:
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
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:
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.
Upvotes: 0
Views: 319
Reputation: 337
I found a solution by using the special variable __file__
.
In the file "macinfo.py" I use the following code to determinate where "companies.pickle" is stored
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
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"))
Upvotes: 1