sh_student
sh_student

Reputation: 389

How to properly set a main working directory for a Python project

Let us assume I have the following folder structure:

/path/to/project/directory/
|- MyProject/
   |- Scripts/
      |- Analysis/
         |- myanalysis.py
      |- Modelling/
         |- mymodel1.py
         |- mymodel2.py
         |- mymodel3.py
      |- Testing/
         |- mytest.py
      |- Function/
         |- myfunction.py
   |- Files/
      |- data.csv

I want to achieve that when running any of the Python scripts, the working directory is always automatically set to /path/to/project/directory/MyProject. It should be a relative path such that someone else can also run the scripts. What would be the best practice to achieve that? Would I need to add a config or ini file? If yes, how would this file need to look like?

I am coming from a R background where you can set R-Projects which automatically set the working directory to the file location of the R-Project file. I want to achieve something like that.

Thanks!

Upvotes: 1

Views: 1681

Answers (1)

GabrielBoehme
GabrielBoehme

Reputation: 322

Many options:

  1. Create virtual env, declare a variable (on a .env file) and use it always as needed
  2. Create a configs.py file and import it everywhere
  3. import os #run this before your code to set current path #(create a function that executes before everything) os.chdir(default_path)

Upvotes: 1

Related Questions