python – How to import .py modules from subfolders to folders

Question:

I have been searching on the net what is the best way to import modules in Python? and I have found these three:

  • Modifying PYTHONPATH .
  • Adding the directory with sys.append("/ruta_directorio") .
  • With a .pth file.

My structure is the following:

project
├── carpeta1
│   ├── __init__.py
│   ├── archivo.py
│   ├── archivo2.py
│   └── subcarpeta1
│       ├── __init__.py
│       └── archivo3.py
└── main.py

The issue is I need to import some archivo.py in archivo3.py . Both carpeta1 and carpeta2 have the __init__.py file.

Could someone tell me what the procedure is for this?

Update (details)

Both folder1 and folder2 have the init.py file.

Answer:

If you're in archivo3.py and want to import some archivo.py just need:

from carpeta1.archivo import foo

Since the main script directory ( main.py ) is in the default PYTHONPATH it is not necessary to modify it. Just import as you would from main.py

Scroll to Top