How to import a Python module from a sibling folder?

痴心易碎 提交于 2019-11-26 12:29:21

问题


I have gone through many Python relative import questions but I can\'t understand the issue/get it to work.

My directory structure is:

Driver.py

A/
      Account.py
      __init__.py

B/
      Test.py
      __init__.py

Driver.py

from B import Test

Account.py

class Account:
def __init__(self):
    self.money = 0

Test.py

from ..A import Account

When I try to run:

python Driver.py

I get the error

Traceback (most recent call last):

from B import Test

File \"B/Test.py\", line 1, in <module> from ..A import Account

ValueError: Attempted relative import beyond toplevel package

回答1:


This is happening because A and B are independent, unrelated, packages as far as Python is concerned.

Create a __init__.py in the same directory as Driver.py and everything should work as expected.



来源:https://stackoverflow.com/questions/14886143/how-to-import-a-python-module-from-a-sibling-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!