How to import python file located in same subdirectory in a pycharm project
Recommended Way:
Make sure to set the working folder as Sources
.
You can do it in Pycharm
->
Preferences
->
Project: XYZ
->
Project Structure
Select your working folder and mark it as Sources
. Then Pycharm recognize the working folder as a Source folder for the project and you will be able to simply add other files within that folder by using
import filename.py
or
from filename.py import mudule1
=================
Not recommended way:
In Pycharm
you can simply add .
before the .py
file which you are going to import it from the same folder. In your case it will be
from .util import my_functions
Resource
There is a good reference also for more information with example how to implement Package Relative Imports. I would highly recommend to check this page.
Package Relative Imports
If you don't have an __init__.py
create one and add this line
from util.util import my_function
then you can easily import the module in your scripts
the __init__.py
tells python that it should treat that folder as a python package, it can also be used to import/load modules too.
in most cases the __init__.py
is empty.
Quoting the docs:
The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case,__init__.py
can just be an empty file, but it can also execute initialization code for the package or set the__all__
variable, described later.