简体   繁体   English

如何从python中的另一个文件夹导入?

[英]How do I import from another folder in python?

I've seen tips on how to import from a subfolder . 我已经看到了有关如何从子文件夹导入的提示。 The problem is importing from another folder in the same parent folder. 问题是从同一父文件夹中的另一个文件夹导入。 The current structure is like this: 当前的结构是这样的:

test 
__init__.py
|-- folder1
|-- __init__.py
| |-- A.py
|-- folder2
| |-- __init__.py
| |-- B.py

A.py is: A.py是:

hi = 1 
print "hi", hi

B.py is: B.py是:

from folder1 import A

print "imported"

When I do python B.py , I get an error: 当我执行python B.py ,出现错误:

  File "B.py", line 1, in <module>
    from folder1 import A
ImportError: No module named folder1

How can I import A.py? 如何导入A.py? Ideally, folder structure does not change. 理想情况下,文件夹结构不会改变。

The problem here is that folder1 and folder2 are subpackages, and the package is the parent directory ie test . 这里的问题是folder1folder2是子包,而该包是父目录,即test

Whatever path the parent directory of test is will need to be in your sys.path . 无论test的父目录是什么路径,都需要在sys.path You can do this, for example, with the PYTHONPATH environment variable. 例如,可以使用PYTHONPATH环境变量来执行此操作。

Then you should have, in module B.py : 然后,您应该在模块B.py

from test.folder1 import A

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

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