简体   繁体   English

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

[英]How to import a file from another folder in Python

I have the following folder structure:我有以下文件夹结构:

...
 │
 ├── src
 │    ├── folder_A
 │    │    └── file_A.py
 │    │    └── __init__.py
 │    │       
 │    ├── folder_B
 │    │    └── file_B.py
 │    │    └── __init__.py
 │    │
 │    └── __init__.py
 │
 │
 └── something else

In the file file_A.py I put from folder_B import file_B as fb .在文件file_A.py我把from folder_B import file_B as fb But file_A.py works only in debug mode (meaning that the code produces the expected results).但是file_A.py只能在调试模式下工作(这意味着代码会产生预期的结果)。 If I run file_A.py in the standard way I get the error ModuleNotFoundError: No module named 'folder_B' .如果我以标准方式运行file_A.py ,则会收到错误ModuleNotFoundError: No module named 'folder_B'

I also changed the configuration before running the code, putting C:\Users\***\***\***\src as the working directory of file_A.py but it still doesn't work.我还在运行代码之前更改了配置,将C:\Users\***\***\***\src作为file_A.py的工作目录,但它仍然不起作用。

What can be a solution?有什么办法可以解决?

If your current directory is src , then folder_B is in the path because of that.如果您的当前目录是src ,那么folder_B因此在路径中。 If you want to make a package with sub-packages that can access each other, place everything into a root package:如果您想制作带有可以相互访问的子包的 package,请将所有内容放入根 package:

 │
 ├── src
 │    └── root_package
 │         ├── folder_A
 │         │    ├── file_A.py
 │         │    └── __init__.py
 │         │       
 │         ├── folder_B
 │         │    ├── file_B.py
 │         │    └── __init__.py
 │         │
 │         └── __init__.py
 │
 └── something else

Now in file_A , you can do现在在file_A ,你可以做

from ..folder_B import file_B as fb

Since src is not a package, you can't do a relative import through it.由于src不是 package,因此您无法通过它进行相对导入。 By adding root_package , you make it possible to find folder_B in the same package hierarchy (albeit a different branch) as the module doing the import.通过添加root_package ,您可以在与执行导入的模块相同的 package 层次结构(尽管是不同的分支)中找到folder_B

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

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