Import Script from a Parent Directory

后端 未结 3 1098
天命终不由人
天命终不由人 2020-11-29 01:20

How do I import a module(python file) that resides in the parent directory?

Both directories have a __init__.py file in them but I still cannot import a

3条回答
  •  有刺的猬
    2020-11-29 01:33

    You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

    In general it is preferable to use absolute imports rather than relative imports.

    toplevel_package/
    ├── __init__.py
    ├── moduleA.py
    └── subpackage
        ├── __init__.py
        └── moduleB.py
    

    In moduleB:

    from toplevel_package import moduleA
    

    If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

提交回复
热议问题