Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including JSON files as part of Python package

I`m writing a package with a "local database" consisting of a folder and subfolders with json files. My database.py module imports these files with a relative path to them (DB_PATH). When installing the package, load fails since files are not found. Is there a way to import those files as part of the package, or a standard way to handle cases like this?

My python code database.py:

DB_PATH = "./db"


def getIndex():
    filename = f"{DB_PATH}/index.json"

    with open(filename) as f:
        data = json.load(f)

    return data

File system:

📦package
 ┣📂folder
 ┃ ┗📂project
 ┃   ┣📂db
 ┃   ┃ ┣ 📜index.json
 ┃   ┃ ┗📂config
 ┃   ┃   ┣ 📜conf_1.json
 ┃   ┃   ┣ 📜conf_2.json
 ┃   ┃   ┗ ...
 ┃   ┗ 📜database.py
 ┗📜setup.py
like image 937
esantix Avatar asked Oct 25 '25 04:10

esantix


1 Answers

If you use a setup.py, add this line:

import glob

setup(
    ...
    data_files=glob.glob('project/db/**')
)

In your database.py

import os.path

DB_PATH = os.path.join(os.path.dirname(__file__), 'db')

The variable __file__ contains the absolute path of the current python script database.py. Use dirname to get the parent folder and join to add database directory in the path.

like image 140
Corralien Avatar answered Oct 27 '25 17:10

Corralien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!