Box
Box
Posts List
  1. Example:
  2. Solve Method

Python3.x load module path error

Program execute display like this error: ImportError: No module named 'xxx' also you used like this code: from .xxx import xxx or from ..xxx import xxx.

Example:

  • module/

    • __init__.py
    • A/

      • __init__.py
      • a.py
        1
        2
        def func():
        print("A.a")
    • B/

      • __init__.py
      • b.py
        1
        2
        3
        4
        from ..A.a import func


        func()
  • main.py

    1
    from module.B import *

This code will display error when running python3 b.py. I think maybe Python3 Interpreter not support this grammar.
And code will display error when running python3 main.py. if you use sys.paths.append("../") or sys.paths.append("./") like this code, still a mistake. Because program when load module abspath is main.py file, not b.py file. And C++ /C language is not such.

Solve Method

  • __file__ return current file path
  • os.path.abspath(path) return file abspath
  • os.path.dirname() return folder abspath
  • os.path.join() join path

load upward one level catalog path: os.path.abspath(os.path.join(os.path.dirname(__file__), "../"))
load upward two level catalog path: os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))

Supporting
Scan, Support Daidai
  • WeChat scan
  • Alipay scan