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.

2
  • It is important so specify which version of Python you're using here. The import mechanism was changed in Python 3. Commented Jun 17, 2018 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 Commented Jun 17, 2018 at 13:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
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.

2 Comments

When the files are growing in numbers gradually, is not wise to put it all in one folder.
I use this method when i have 1 or 2 files extra

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.