Run python commands within the project directory without running into file does not exist error

Question:

Project structure:

├── main.py
└── utils
    ├── assets
    │   ├── export.csv
    ├── client.py

utils/client.py code snippet:

df = pd.read_csv("/assets/export.csv")

command within project root: python utils/client.py

FileNotFoundError: [Errno 2] No such file or directory: '/assets/export.csv'

I want to make this code robust to avoid adding absolute path which will change from machine to machine.

Quesiton : How to import project root directory path in this place-holder in utils/client.py so that I can run the command mentioned above from anywhere within the project directory so that I don’t run into this error.

FileNotFoundError: [Errno 2] No such file or directory: '/assets/export.csv'

Something like this in utils/client.py

from ../main.py import PROJECT_DIR_PATH
df = pd.read_csv(f"{PROEJECT_DIR_PATH}/utils/assets/export.csv")

and in main.py

PROJECT_DIR_PATH = os.getcwd()
Asked By: sikepike

||

Answers:

You can use the ´__file__´ attribute to access the path of your main module. https://docs.python.org/3/reference/import.html?highlight=__file__#file__

import os

PROJECT_PATH = os.path.dirname(os.path.abspath(__file__))
Answered By: Mathieu Roze
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.