DEV Community

Jason Cruz
Jason Cruz

Posted on

First time writing Python with sub-directories?

Are you writing your first Python program, and you have folders within folders, within folders?

Pretty Simple

I'd like to learn how to run my own Image Recognition software using Python. I started with making a new file, and I named it main.py. Im thinking its going to be easy like what you see on YouTube. Ahhh ya.. not so much.

Did you know, that when you have a file structure like this:

  • user/desktop/src/Lib/site-packages

and in your code you would like to import a package from site-packages but your main.py file you just made is in your src folder. Just importing like this isnt enough.

import PySimpleGUI
Enter fullscreen mode Exit fullscreen mode

Because once you run and complie your main.py file, you will most likely get a error that says something like this:

ImportError: cannot import name 'PySimpleGUI' (unknown location)
Enter fullscreen mode Exit fullscreen mode

Then it hits you. You are the worse programmer that ever exists. Don't worry, I was there today..

GUESS WHAT!?

It's just imposter syndrome kicking in, you are not a failure.

Matter of fact, something I discovered that took me 3 hours to find was a tiny little file called:

__init__.py

Believe it or not, this file is in every folder that has some kind of python file. Supposely, for everwhere you want your code at, or where your packages are, you need an __init__.py file. EVEN if the file is blank.

The init.py file lets the Python interpreter know that a directory contains code for a Python module. An init.py file can be blank. Without one, you cannot import modules from another folder into your project.

YOUR WELCOME!!

I know right!? Could it have been that easier with everything else in life.. If only!


So next time you get stuck in Python and you cant run/compile your code, hopefully you remember did you add an init.py file to your directories yet?

Hopefully, you do from now on.

Save this post! It will save your life from the aggervation you will find yourself in.. lol

Thanks everyone for reading.

Top comments (0)