简体   繁体   中英

importing file in python through multiple directories

I have a directory structure like this in python:

- __init__.py (1)
- folder1
    - __init__.py (2)
    - folder2
        - __init__.py (3)
        - file.py

how can I expose file.py?

currently in __init__.py(2) I have:

from folder2 import file

do I have to add in __init__.py(1)

from folder1 import file

and do I have to add anything to __init__.py(3) ?

These are all the imports you could do (you are not required to perform all of them, just the ones you need):

in __init__.py (1):

from .folder1.folder2 import file

in __init__.py (2):

from .folder2 import file

in __init__.py (3):

from . import file

Beware that if you actually run one of those __init__.py files, the actual name for the running file will be "__main__" and the relative import will not work. If you intention is that, remove the first dot in the respective import sentence. However it is not always the best practice to run an in-package file because of this issues, but if you do, take note of this.

Alternatively you can do:

in __init__.py (1):

from .folder1 import file

as long as you do also in __init__.py (2):

from .folder2 import file

But you are not required to do that. However it is useful when you want to use file both in the __init__.py (2) and __init__.py (1). But if you don't need to use file in (2) then you can refer to first alternative.

myproject
  |-app.py
  |-__init__.py
  |-folder1
      |-__init__.py
      |-folder2
         |-__init__.py
         |-file.py

for example, we have app.py under folder project. In app.py, put the following lines on the top:

import sys
sys.path.append("/path/to/myproject")  # tells interpreter your myproject path
from folder1.folder2 import file  # imports your file.py module

you dont have to modify the __init__.py files, just leave them empty and no matter how many python directories you have , you can always imports them in this way

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