简体   繁体   English

如何从同级文件夹导入 Python 模块?

[英]How to import a Python module from a sibling folder?

I have gone through many Python relative import questions but I can't understand the issue/get it to work.我已经经历了许多 Python 相关导入问题,但我无法理解问题/让它工作。

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

This is happening because A and B are independent, unrelated, packages as far as Python is concerned. 之所以发生这种情况,是因为就Python而言, AB是独立的,无关的软件包。

Create a __init__.py in the same directory as Driver.py and everything should work as expected. 在与Driver.py相同的目录中创建一个__init__.py ,所有操作均应按预期进行。

In my case adding __init__.py was not enough.在我的例子中,添加__init__.py是不够的。 You also have to append the path of the parent directory if you get module not found error.如果您收到模块未找到错误,您还必须 append 父目录的路径。

root :
 |
 |__SiblingA:
 |    \__A.py
 |     
 |__SiblingB:
 |      \_ __init__.py
 |      \__B.py
 |

To import B.py from A.py, you have to do the following要从 A.py 导入 B.py,您必须执行以下操作

import sys
  
# append the path of the parent directory
sys.path.append("..")

from SiblingB import B
print("B is successfully imported!")

The reason for的原因

ValueError: Attempted relative import beyond toplevel package

is that A is the same directory level as Driver.py .ADriver.py处于同一目录级别。 Hence, ..A in from..A import Account is beyond top-level package.因此, ..A in from..A import Account超出了顶级 package。

You can solve this by create a new folder named AandB together with __init__py in this new folder, and then move A and B folders into AandB folder.您可以通过在这个新文件夹中创建一个名为AandB的新文件夹和__init__py来解决这个问题,然后将AB文件夹移动到AandB文件夹中。 The directory structure is as following:目录结构如下:

目录结构

Correspondingly, the content in Driver.py should be modified as from AandB.B import Test .对应的, Driver.py中的内容修改为from AandB.B import Test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM