-1

I want to import different folders as modules.

My folder structure is like this:

/project
    /movies
        get_genres.py
    /mysql
        /movies
            insert_genres.py

In my insert_genres.py script I import:

import movies.get_genres as moviegenres

def main():
    for key, value in moviegenres.items():
        print(key)

main()

And i get error like this:

import movies.get_genres as moviegenres
ModuleNotFoundError: No module named 'movies'

I opened empty __init__.py file in each folder but it didn't work.

Ulaş
  • 11
  • 3
  • Looks like a duplicate of https://stackoverflow.com/q/279237/4450498 and https://stackoverflow.com/q/72852/4450498 – L0tad May 01 '23 at 20:32
  • 1
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – TomServo May 01 '23 at 20:37

1 Answers1

-1

Your folder structure is not being recognised as a package because you don't have any init.py files in your directories. The init.py files are required to let Python know that the directory should be treated as a package.

Folder structure should look like this:

/project
    /movies
        __init__.py
        get_genres.py
    /mysql
        /movies
            __init__.py
            insert_genres.py

Create empty init.py files in both the /movies and /mysql/movies folders.

Update the sys.path in your insert_genres.py file to include the parent directory, so that Python can find the movies package:

import sys
import os

# Add the parent directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import movies.get_genres as moviegenres

def main():
    for key, value in moviegenres.items():
        print(key)

main()
FreddyC08
  • 51
  • 2