How to make a python script containing file paths independently executable as well as importable?

Viewed 192

There are several filepaths in a python script such as

ner_model = '../jd_ner_june19.ser.gz'
word2vec_model = '..\\Word2Vec\\model-100-5-6-11June.pkl'

When the script is imported and used by another script for example a script in the parent directory , FileNotFoundError occurs.

Is there a standardized way to handle such situations ? The end goal is to deploy the package in a docker

2 Answers

You can compose the file name as the following, assuming those paths are relative to your script filename:

import os.path

myfile = os.path.join(os.path.dirname(__file__), 'my/file/path.txt')

Another approach is to look at Pathlib which provides an OO way of dealing with paths in an OS-independent way.

Related