0

I have a folder structure as below

root
  ->module
    -> __init__.py
    -> lib
       -> data.pk
    -> read.py
  ->script
     -> __init__.py
     -> inner.py
  ->outer.py

read.py has below code

with open(r"./lib/data.pk", "rb") as f:
    data = pickle.load(f)`

Now when I import module.read in outer.py file, it successfully opens ./lib/data.pk file

However when I try to import module.read in inner.py file, i get an error Module does not exist: 'module.read'

I then appended the parent directory to sys.path using below code

PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(PROJECT_ROOT)

and the I was able to import module.read successfully. However when I execute the inner.py file I get an error No such file or directory: './lib/data.pk'

Since I have added the parent directory to sys.path, I was expecting inner.py to open and read './lib/data.pk' file.

Kindly let me know, how can I read './lib/data.pk' file from inner.py file

1 Answers1

0

Change code to this:

with open(os.path.dirname(__file__)+"/lib/data.pk", "rb") as f:


If this doesn't work, follow the steps below:

Add this to inner.py in the beggining:

import sys
sys.path.insert(0, '../')

And add an __init__.py to the root folder.

Read more from here: How to import a module from a different folder?

LoukasPap
  • 1,244
  • 1
  • 8
  • 17