irahorecka
irahorecka

Reputation: 1807

Setting consistent home directory for python files

I am writing a python script that has dependencies on directories within its repository. I want to learn a way to create a home directory that is always central to the repository directory. This should be versatile for anybody who wishes to clone this repository on his or her server.

The script accesses its dependent directories just fine when I run the script IN the repository directory. If I were to run the script outside of the repository directory, a FileNotFoundError exception is thrown. What is the best way to circumvent this issue?

# if I run this in the repo directory, it works just fine

import os.path
base_dir = os.getcwd()
csv_dir = f'{base_dir}/CSV'

# however, if I run this in a directory outside of the repository (e.g.
# $ python dir1/dir2/file.py ), a FileNotFoundError is thrown.

Upvotes: 1

Views: 178

Answers (1)

Lord Elrond
Lord Elrond

Reputation: 16032

os.getcwd() returns the working directory, which is the dir that the script is being ran in, not the dir of the repository.

Instead you should use:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

Upvotes: 1

Related Questions