1

Here's my project structure

- folder_1
    - folder_2  
        - file1.py
        - file2.py

    - folder_3
        - file3.py

Now I use this command to run file1.py

python folder_1/folder_2/file1.py

But what I found is that python put folder_1/folder_2 into PYTHONPATH. What I want is also put folder_1 into PYTHONPATH, so that file_1.py can import functions into file3.py. Although I can populate PYTHONPATH by myself, I just wonder whether there is any convenient or standard way to do that, because I believe it is a very common scenario.

1 Answer 1

1

You can use sys.path in your script:

import sys, os

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) # Get the absolute path of the project root directory
sys.path.append(project_root)

Now you can import modules from the root or other folders like this:

import folder_3.file3

So your code will look like this:

import sys, os
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')) # Get the absolute path of the project root directory
sys.path.append(project_root) # Add it to the directories where python will search for modules while importing

import folder_3.file3
Sign up to request clarification or add additional context in comments.

2 Comments

Is this the standard way to do that? My scenario is I want to arbitray python file in my project which is a very common scenario. Does that mean I have to do this for every file?
Using sys is the most common and straightforward approach I know. sys is part of Python's standard library, making it readily available in any Python environment. While there are alternative methods to this, they tend to be more complex and less straightforward compared to using sys.path.

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.