1

Let's say I have a python package called my project. Inside this directory, I have two other directories named run_files and code_files. So the file structure is as follows:

->my project
      |
      |___________
      |           ->run_files
      |                |
      |                |_________run.py
      |
      |___________
                  -> code_files
                       |
                       |_________codes.py   

As the names suggests run_files contains the python file (like run.py) where I am going to execute my python program while code_files contains other files (like code.py) where the main codes of my program exist. Clearly, I need to import some of the files inside the code_files directory to run my program.

However, the problem is that because of this structure I get import error since when python wants to run it, it looks into the parent directory and tries to find the files with root run_files. How can I change this with a code inside my python file run.py instead of resorting to changing it on terminal.

3
  • I suggest restructuring your code slightly. Put the script you intend to run directly under my project, and have it import code you need from run_files. Your actual script may be no more than import run_files; run_files.run.go(), where run.go is just your script-level code wrapped in a function to serve as an entry point. Commented Mar 25, 2019 at 17:32
  • Any reason not to create it as an actual module package and install it with -e (editable)? Commented Mar 25, 2019 at 17:36
  • If any of the answers solved your question, it's good practice to upvote and accept. The latter also grants you a small rep bonus. Commented Mar 25, 2019 at 18:22

1 Answer 1

2

The easiest way to access any file on your computer is probably sys.path

# code_file.py
import sys
sys.path.insert(0, 'location/of/code_files')

import code_file

You can also use append() instead of insert():

sys.path.append('location/of/code_files')
Sign up to request clarification or add additional context in comments.

2 Comments

Hi @alec935, I need to test it on my server to see it works. Thanks for answering. If it solves my problem then sure I am going to accept and up vote it. Please wait till tomorrow.
No problem! I just like leaving that comment because people forget :)

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.