0

I currently have the following directory structure:

Folder/
  package/
      __init__.py, .. many python files
  subfolder/
       file1.py

Now, my problem is that I am in the Folder directory. I can run python and then run import package. This works fine. However, in my file1.py, I import package at the beginning but when I run python subfolder/file1.py, it cannot find module named package.

Edited: I currently have __ init__.py (with 2 underscores)

3
  • How do you import your package in file1.py ? Commented Sep 30, 2016 at 10:27
  • 1
    Renaming _init_.py to __init__.py should help you out Commented Sep 30, 2016 at 10:34
  • I suspect the underscores are a typo: the problem will remain even if they are fixed. Commented Sep 30, 2016 at 10:36

2 Answers 2

2

In the latter case, Python cannot find package because it is not visible on sys.path. sys.path will contain amongst other things the parent directory of the script currently being executed.

So when you run Python from Folder, this entry is /path/to/Folder and import package correctly finds the package directory from this. In your second case, this entry will be /path/to/Folder/subfolder and import package will fail because it tries to find /path/to/Folder/subfolder/package.

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

1 Comment

It's difficult to answer this question without knowing what you're trying to achieve. You can manipulate sys.path inside a script to bring the right packages into scope (i.e. by adding /path/to/Folder to sys.path in file1.py before importing package), but often a rethink of your architecture is a better approach.
0

Rename _init_.py to __init__.py (two underscores)

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.