How do I import other Python files?

22    Asked by 1word4_8160 in Python , Asked on May 11, 2025

How do I import other Python files into my script? Learn the different ways to reuse code from other Python files using import, from ... import, and how to manage modules and paths effectively.

Answered by Neha Tambe

Importing other Python files into your script is a great way to keep your code organized and reusable. Python makes this easy through its built-in module system. If you have functions or classes in another file, you can bring them into your current file with just a few lines of code.

1. Using import:

If you have a file named utils.py, you can import the entire file like this:

import utils
utils.say_hello()

This imports the whole file, and you access its functions or variables using dot notation.

2. Using from ... import:

To import specific parts from another file:

from utils import say_hello
say_hello()

Cleaner and more direct, especially if you only need one or two items.

3. Importing from a folder (package):

If your file is in a subfolder, you need an __init__.py file (can be empty) in that folder to treat it like a package:

project/
├── helpers/
│ ├── __init__.py
│ └── tools.py

Then import like this:

  from helpers import tools

4. Using relative or absolute paths:

You can also manage paths with Python’s sys module if your file isn’t in the same directory:

import sys
sys.path.append('/path/to/your/file')
import custom_module

Using imports helps keep your code DRY (Don't Repeat Yourself) and modular. Once you get the hang of it, importing files becomes second nature in Python development.



Your Answer

Interviews

Parent Categories