How to Import a Python File from the Same Directory?

In this tutorial, I will explain how to import a Python file from the same directory as your current script. As a developer recently I came across a scenario where I needed to import a file from the same directory. After researching I found some important methods to achieve this task, I will explain them with examples.

Import a Python File from the Same Directory

One common issue developers face when importing Python files is dealing with files that have the same name as a directory. For example, let’s say you have a directory called “users” and a Python file named “users.py” within that directory. If you attempt to import the “users.py” file from another script in the same directory, you might encounter some confusion

To illustrate this, consider the following directory structure:

project/
    users/
        __init__.py
        users.py
    main.py

In the “main.py” script, if you try to import the “users.py” file using the statement import users, Python will prioritize the “users” directory over the “users.py” file. This can lead to unexpected behavior and import errors.

Read How to Get File Size in Python?

Solution: Relative Imports

To overcome this naming conflict and successfully import a Python file from the same directory, you can utilize relative imports. Relative imports allow you to specify the location of the file relative to the current script.

Here’s how you can modify the import statement in “main.py” to correctly import the “users.py” file:

from .users import users

By prefixing the import statement with a dot (.), you indicate that you want to import from the same directory as the current script. This tells Python to look for the “users.py” file within the same directory, resolving the naming conflict.

Read How to Write a Variable to a File in Python?

Import from Subdirectories

In some cases, you may need to import a Python file located in a subdirectory relative to your current script. To accomplish this, you can extend the relative import syntax.

Consider the following directory structure:

project/
    utils/
        __init__.py
        helpers.py
    main.py

To import the “helpers.py” file from the “utils” subdirectory in your “main.py” script, you can use the following import statement:

from .utils.helpers import calculate_age

This statement tells Python to look for the “helpers.py” file within the “utils” subdirectory relative to the current script and import the calculate_age function.

Check out How to Check If a File Exists and Create It If Not in Python?

Handle Missing init.py Files in Python

In Python 2.x, directories required an “init.py” file to be considered as packages and allow imports from them. However, starting from Python 3.3, the presence of an “init.py” file is no longer mandatory for importing from directories.

If you encounter a situation where you need to import from a directory that doesn’t contain an “init.py” file, you can still use relative imports as described earlier. Python will treat the directory as a namespace package and allow imports from it.

Read How to Get the File Size in MB using Python?

Best Practices for Importing Files in Python

When importing Python files, it’s important to follow some best practices to keep your code organized and maintainable:

  1. Use meaningful and descriptive names for your files and directories to avoid confusion.
  2. Avoid naming conflicts by ensuring that your file names don’t clash with existing module names or reserved keywords.
  3. Follow the Python convention of using lowercase letters and underscores for file names (e.g., “user_utils.py”).
  4. Use absolute imports for modules installed via pip or other package managers to ensure clarity and avoid potential issues.

Examples of Importing Files
Let’s look at a few examples of importing Python files from the same directory and subdirectories.

Check out How to Unzip a File in Python?

Example 1: Import a specific function from a file

from calculator import add_numbers

result = add_numbers(5, 7)
print(result)  

Output:

12

You can look at the output in the below screenshot.

Import a Python File from the Same Directory

In this example, we import the add_numbers function from the “calculator.py” file located in the same directory as the current script. We can then use the imported function directly.

Read How to Read Tab-Delimited Files in Python?

Example 2: Import an entire file as a module

from user_manager import create_user  

user = create_user("John", "Doe", "john@example.com")
print(user) 

Output:

User(first_name='John', last_name='Doe', email='john@example.com')

You can look at the output in the below screenshot.

How to Import a Python File from the Same Directory

Here, we import the entire “user_manager.py” file as a module using the from . import user_manager statement. We can access the functions and classes defined in the “user_manager.py” file using the module name.

Check out How to Split a File into Multiple Files in Python?

Example 3: Import from a subdirectory

from .utils.validators import is_valid_email

email = "jane@example.com"
if is_valid_email(email):
    print("Valid email address")
else:
    print("Invalid email address")

In this example, we import the is_valid_email function from the “validators.py” file located in the “utils” subdirectory relative to the current script. We can use the imported function to validate an email address.

Check out How to Skip the First Line in a File in Python?

Conclusion

In this article, I helped you to learn how to import a Python file from the same directory. I explained relative import , importing from subdirectories , and how to handle missing init.py files. I also covered some best practices for importing files along with examples.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.