Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: import a file from another directory

I am working in a set of directories with the following structure:

Master/
      Subfolder_1/file_1_1.py
                  file_1_2.txt
      Subfolder_2/file_2_1.py

I import file_1_1 in file_2_1 as follows:

import sys
sys.path.append('../file_1_1')

file_1_1 is reading file_1_2.txt which is in the same directory. However, when I call the function that reads file_1_2.txt from file_2_1.py, it says no such file and directory and it gives me the path of file_1_2.txt as:

Master/Subfolder_2/file_1_2.txt

which is a wrong path. It seems like python in this case is using the working directory as a reference. How can I solve this error given that I don't want to include the absolute path for each file I read.

like image 388
user1894963 Avatar asked Jan 30 '26 09:01

user1894963


1 Answers

Don't mess with sys.path, and don't think of imports as working against files and directories. Ultimately everything has to live in a file somewhere, but the module hierarchy is a little more subtle than "replace dot with slash and stick a .py at the end".

You almost certainly want to be in Master and run python -m Subfolder_1.file_1_1. You can use pkg_resources to get the text file:

pkg_resources.resource_string('Subfolder_1', 'file_1_1.txt')
like image 119
Eevee Avatar answered Feb 01 '26 23:02

Eevee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!