0

My dummy project tree is as below:

base|
    |test.py
    |model
         |code1.py
         |code2.py
         |hi.npy

hi.npy is a simpe string stored / any file that I need to load in code1.

code2.py

import numpy as np 

def pr(a):
    print(f'hi {a}')

code1.py

from code2 import pr # I load the function from code2
import numpy as np 
a = np.load('hi.npy') # I try to load the file

When I'm inside model, I can run both code1 and code2 without any issue.

But when I go one level up, to the base folder.

test.py

import sys
from pathlib import Path

sys.path.append(Path(__file__).parent / "model")

print(sys.path)

from model.code1 import *

Even though I'm adding the model path to the system as suggested by many similar answers (Python: Best way to add to sys.path relative to the current running script), neither the pr function nor the a file is loaded successfully from test.py.

ModuleNotFoundError: No module named 'code2'

FileNotFoundError: [Errno 2] No such file or directory: 'hi.npy'

I can change the design of the file structure/move the files/use OOP to fix the issue but is there anything much simple method that enables me to load both a and pr from test.py

1. without manually changing file paths/imports inside code1, code2 and

2. be able to run test.py (from base) and code1.py (from model) simultaneously.

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60

0 Answers0