ARASH
ARASH

Reputation: 428

Pythonic-way to append path to several files in the project

I am working on a python project consisting several folders and .py files.
For all files, I have to use sys.path.append to introduce my the project directory before importing files from other folders. This makes it troublesome if I want to run the code on another PC. I'd like to want to know if there is a better way so that I don't need to update sys.path.append in files when running on another PC?

Upvotes: 1

Views: 266

Answers (1)

goodvibration
goodvibration

Reputation: 6206

You can use sys.path.append with a relative path, not with an absolute path.

Here is how I do it in one of my projects:

Create file Config.py:

import sys,os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

And import this file in each one of the other files in your project.

Note that os.path.dirname(os.path.dirname(__file__)) is just an example.

Upvotes: 1

Related Questions