The most Pythonic way to import a module from another folder is to place an empty file named __init__.py
into that folder and use the relative path with the dot notation.
For example, a module in the parent folder would be imported with from .. import module
. The __init__.py
file signals to Python that the folder should be treated as package.
Problem Formulation
Problem: How to import a file or a module from another folder or directory in Python?
Example: Say, you’ve given the following folder structure:
application
βββ app
β βββ folder
β βββ file_1.py
βββ app2
βββ some_folder
βββ file_2.py
Your goal is to import functions from file_1.py
in file_2.py
.
Method 1: sys.path.append()
The first method appends the path of the file_1.py
to the system’s path
variable.
# file_2.py import sys sys.path.append('/.../application/app/folder') import file_1
Note that you need to replace the first three dots in '/.../application/app/folder'
with the concrete path to the applications
folder.
By the way, feel free to join my free email academy and download your Python cheat sheets here:
It’s fun–and thousands of Finxters have told me that they love the cheat sheets!
Okay, let’s move on to a slightly modified solution to this problem:
Method 2: sys.path.insert()
A similar alternative is to insert the path of file_1.py
to position 1 of the system’s path
variable.
This ensures that it’s loaded with higher priority and avoids some naming conflicts:
# file_2.py import sys sys.path.insert(1, '/.../application/app/folder') import file
Again, replace the first three dots in '/.../application/app/folder'
with the concrete path to the applications
folder.
Method 3: Dot Notation with __init__.py
You can also do the following trick—creating a new package.
# file_2.py from application.app.folder.file_1 import func_name
However, make sure to include an empty __init__.py
file in the directory.
This file tells Python to treat the directory as a package. I’d consider this to be the most Pythonic way of solving this problem.
Method 4: Importlib
A not-so Pythonic alternative — it’s more clunky and is based on external dependencies — would be to use the importlib
module.
Here’s an example:
import importlib.util as ilu folder = '/.../application/app/folder' file = 'file_2' spec = ilu.spec_from_file_location(file, folder) your_lib = ilu.module_from_spec(spec) spec.loader.exec_module(your_lib) your_lib.function()
Related Video
Feel free to watch the following explainer video where Finxter Creator Peter shows you how to call a function from another file:
References
- https://stackoverflow.com/questions/4383571/importing-files-from-different-folder
- https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?rq=1
- How to Import a Python Function from another Folder
Where to Go From Here?
Enough theory. Letβs get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. Thatβs how you polish the skills you really need in practice. After all, whatβs the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
π If your answer is YES!, consider becoming a Python freelance developer! Itβs the best way of approaching the task of improving your Python skillsβeven if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar βHow to Build Your High-Income Skill Pythonβ and learn how I grew my coding business online and how you can, tooβfrom the comfort of your own home.
More Finxter Tutorials
Learning is a continuous process and you’d be wise to never stop learning and improving throughout your life. π
What to learn? Your subconsciousness often knows better than your conscious mind what skills you need to reach the next level of success.
I recommend you read at least one tutorial per day (only 5 minutes per tutorial is enough) to make sure you never stop learning!
π‘ If you want to make sure you don’t forget your habit, feel free to join our free email academy for weekly fresh tutorials and learning reminders in your INBOX.
Also, skim the following list of tutorials and open 3 interesting ones in a new browser tab to start your new — or continue with your existing — learning habit today! π
Python Basics:
- Python One Line For Loop
- Import Modules From Another Folder
- Determine Type of Python Object
- Convert String List to Int List
- Convert Int List to String List
- Convert String List to Float List
- Convert List to NumPy Array
- Append Data to JSON File
- Filter List Python
- Nested List
Python Dependency Management:
- Install PIP
- How to Check Your Python Version
- Check Pandas Version in Script
- Check Python Version Jupyter
- Check Version of Package PIP
Python Debugging:
Fun Stuff:
- 5 Cheat Sheets Every Python Coder Needs to Own
- 10 Best Python Puzzles to Discover Your True Skill Level
- How to $1000 on the Side as a Python Freelancer
Thanks for learning with Finxter!
Programmer Humor
Q: How do you tell an introverted computer scientist from an extroverted computer scientist?
A: An extroverted computer scientist looks at your shoes when he talks to you.