3

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.

2 Answers 2

1

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')
Sign up to request clarification or add additional context in comments.

2 Comments

I actually run file_2_1 which uses file_1_1. So do you mean to run python -m Subfolder_2.file_2_1 ? If this is the case, I get this error: No module named Subfolder_2.
put an __init__.py in each "subfolder" so they both become packages.
0
info=[]
with open(os.path.realpath('yourtextfile.txt','r') as myfile:
    for line in myfile:
       info.append(line)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.