0

I have no idea why my import doesnt work.

My folder structure

Garage_Parking
    __init__.py
    database.py

    rpi_components
        __init__.py
        NFC_Security.py

I want to import database in NFC_Security.py. I typed

from Garage_Parking import database

It just keep giving me this error

Traceback (most recent call last):
 File "NFC_Security.py", line 6, in <module>
from Garage_Parking import database

ImportError: No module named Garage_Parking

I appreciate any help.

LiveaLearn
  • 177
  • 5
  • 18
  • It is important so specify which version of Python you're using here. The `import` mechanism was changed in Python 3. – Roland Smith Jun 17 '18 at 13:40
  • @RolandSmith, when I do python --version is 2.7.9. But when I do a dpkg -l python3, there is a python 3.4 installed – LiveaLearn Jun 17 '18 at 13:43

2 Answers2

1

The idea is to add the path of the parent folder to the python path so that the interpreter knows that it should look for files and modules even in the parent directory.

import os,sys
current_directory = os.getcwd()
parent_directory = os.path.dirname(current_directory)
sys.path.insert(0, parent_directory)

The code above adds the parent directory to the python path. Now you can freely import all modules from the parent folder. Complete code for your specific case:

import os,sys
current_directory = os.getcwd()
parent_directory = os.path.dirname(current_directory)
sys.path.insert(0, parent_directory)

import database

For more information visit Importing modules from parent folder

0

You could try putting the main file with the rest of the files and then doing import database. It is the easy way. If you would like to keep your folder organization, I can’t help you.

Trooper Z
  • 1,617
  • 14
  • 31