user1894963
user1894963

Reputation: 665

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.

Upvotes: 3

Views: 1085

Answers (2)

ethan
ethan

Reputation: 1

info=[]
with open(os.path.realpath('yourtextfile.txt','r') as myfile:
    for line in myfile:
       info.append(line)

Upvotes: 0

Eevee
Eevee

Reputation: 48564

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')

Upvotes: 1

Related Questions