最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

"No Module named" error - Python File organization - Stack Overflow

programmeradmin3浏览0评论
src
|
----folder1
     |------file.py
----folder2
     |------file2.py

Now If I try to access file from file2 I get No Module Named Error.

from folder1.file import *

What can I do to fix this?

src
|
----folder1
     |------file.py
----folder2
     |------file2.py

Now If I try to access file from file2 I get No Module Named Error.

from folder1.file import *

What can I do to fix this?

Share Improve this question asked Mar 15 at 20:08 Rishabh AgarwalRishabh Agarwal 334 bronze badges 4
  • 2 You can use .. in the import statement to indicate a parent directory. Try from ..folder1.file import *. – John Gordon Commented Mar 15 at 20:11
  • Make sure you have a (possibly empty) __init__.py file in each directory you're importing stuff from, to tell Python it's a package. – joanis Commented Mar 15 at 22:17
  • stackoverflow/q/4383571/26993270 – Man made of meat Commented Mar 16 at 3:00
  • Yup tried this - didnt work. Even adding empty __init__.py didn't work. I had to restructure my code a lot and then use a setup.py to basically create a package and then use pip install -e . to make the package editable @JohnGordon @joanis – Rishabh Agarwal Commented Mar 16 at 23:53
Add a comment  | 

2 Answers 2

Reset to default 0

So I'm back - restructuring the code fixed the problem:

src
|
----setup.py
----primary_folder
     |
     ----__init__.py
     ----folder1
         |------file.py
         |------__init__.py (empty)
     ----folder2
         |------file2.py
         |------__init__.py (empty)

The code for the setup.py is :

from setuptools import setup, find_packages

setup(
    name="primary_folder",
    version="1.0",
    packages=find_packages(),
    author="John Doe",
    install_requires=[
        # Add other dependencies
    ],
)

Then ran the command pip install -e . to make the package primary_folder editable and use it (whenever new code is added - need to rerun this) and import statements become from primary_folder.folder1.file import *

Hope this helps people with similar problems. Python folder usage is problematic.

from ..folder1.file import *

Try this

发布评论

评论列表(0)

  1. 暂无评论