Importing From A File In Another Folder Which Is At The Same Level Of A Project's Structure
I've searched far and wide for how to do this, without success. Imagine I have a project structure like this: my_proj - notebooks - - a_notebook_into_which_i_want_to_import_a_class
Solution 1:
You essentially need to inform Python where it needs to look for that class you want to import. You can check the list of default locations by printing sys.path
in a script. Usually, this is a couple of standard locations including the python install directory itself. It will also check in the directory that the currently running script is present in.
Since you can't move that other file into the same directory, you can either add it to the PYTHONPATH
environment variable (which makes it accessible to all scripts on your machine) or use the following snippet in order to load it only for your particular script.
The snippet adds the path only for the duration of your script, and doesn't make any persistent changes.
import os
import sys
from pathlib import Path
# to get the path of currently running script
path = Path(os.path.realpath(__file__))
# path.parents[0] gets the immediate parent dir (notebooks/)
# path.parents[1] is 2 levels up, i.e. my_proj/
# use path.join to get abspath of src/, and then add it to sys.path
sys.path.append(os.path.join(path.parents[1], 'src'))
from a_file_with_the_class_i_want_to_import import DesiredClass
# You should be able to use it now
Post a Comment for "Importing From A File In Another Folder Which Is At The Same Level Of A Project's Structure"