简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM