简体   繁体   中英

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 . But file_A.py works only in debug mode (meaning that the code produces the expected results). If I run file_A.py in the standard way I get the error 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.

What can be a solution?

If your current directory is src , then folder_B is in the path because of that. If you want to make a package with sub-packages that can access each other, place everything into a root 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

from ..folder_B import file_B as fb

Since src is not a package, you can't do a relative import through it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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