W3docs

Importing files from different folder

To import a module from a different folder in Python, you can use the sys.path.append() function to add the path to the folder containing the module to your Python path.

To import a module from a different folder in Python, you can use the sys.path.append() function to add the path to the folder containing the module to your Python path.

Here's an example:

import a module from a different folder in Python

import sys
from pathlib import Path
# Add the target folder to the Python path (cross-platform)
sys.path.append(str(Path(__file__).resolve().parent / 'target_folder'))
import module

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

You can also use the PYTHONPATH environment variable to specify directories that should be searched for modules. To do this, you can set the PYTHONPATH environment variable to a list of directories separated by : on Unix-like systems (e.g., Linux, macOS), or ; on Windows.

For example, to set the PYTHONPATH variable on Unix-like systems:

set the PYTHONPATH variable on Unix-like systems

export PYTHONPATH=$PYTHONPATH:/path/to/folder

Or, on Windows:

set the PYTHONPATH variable on Windows

set PYTHONPATH=%PYTHONPATH%;C:\path\to\folder

Then, you can import the module using import module as usual.

Best practices and notes:

  • Python searches directories in the order they appear in sys.path or PYTHONPATH, stopping at the first match.
  • sys.path.append() works but is generally discouraged in production. Prefer creating an __init__.py file in the target folder to make it a proper package, or use relative imports within a project structure.
  • PYTHONPATH takes precedence over pip-installed packages and is typically managed within virtual environments to avoid conflicts.