When importing a dependency script acts as it is in a different directory

Viewed 38

I have the following directory:

project
|
├──folder1
│ └── text_to_use.txt
│ └── file.py
|
├──folder2
| └──file_to_import.py
|
└──more_files.py

file.py is using text_to_use.txt and usually works fine.
When importing file_to_import.py, file.py starts acting as if inside project instead of folder1.

file.py code:

from folder2.file_to_import import some_class
open("text_to_use.txt", 'r')

Error:

FileNotFoundError: [Errno 2] No such file or directory: 'text_to_use.txt'

note: I'm using PyCharm. this also happens when I import the same dependency with other files in folder1.

I'm looking for an elegant solution, not something like:

import sys
sys.path.append('folder2.file_to_import')
1 Answers

file.py

from pathlib import Path

pa_to_use = Path(__file__).parent.parent / "folder2" / "text_to_use.txt"

with pa_to_use.open() as f_use:
  stuff = f_use.read()


Related