To import a file from another folder in Python, the most reliable method is to add the target folder's path to sys.path using sys.path.append() or by treating the folder as a package using __init__.py files and dot notation. Python's import system searches for modules in a specific list of directories; if your file is outside the current working directory or the standard library paths, you must explicitly tell Python where to look.
What You'll Need
- Python installed on your system (Python 3.x is recommended).
- A code editor or IDE (such as VS Code, PyCharm, or Sublime Text).
- A project directory containing at least two separate folders to demonstrate the cross-folder import.
- Basic familiarity with how Python files (.py) and directories work.
Step-by-Step
- Organize Your Directory Structure: Before writing code, establish a clear folder hierarchy. For this example, create a main project folder. Inside that folder, create two subfolders: one named
scripts(where your main execution file will live) and one namedmodules(where the file you want to import will live). Place a file namedhelper.pyinside themodulesfolder and a file namedmain.pyinside thescriptsfolder. - Create the Target Module: Open
helper.pyand add a simple function so you can verify the import works. For example, writedef greet(): print("Hello from the other folder!"). Save the file. - Method A: Using sys.path (The Dynamic Approach): This is the most direct way to import from any arbitrary location on your hard drive. Open
main.pyand import thesysmodule. Usesys.path.append()to add the absolute path of themodulesfolder to the list of directories Python searches.
Example code:import sys import os
Get the absolute path to the 'modules' folder
This assumes 'modules' and 'scripts' are siblings in the same parent directory
current_dir = os.path.dirname(os.path.abspath(__file__)) parent_dir = os.path.dirname(current_dir) module_path = os.path.join(parent_dir, 'modules') sys.path.append(module_path) import helper helper.greet() - Method B: Using Package Notation (The Structured Approach): If your project is designed as a package, you can use dot notation. First, ensure that both the root directory and the
modulesfolder contain a file named__init__.py. This file can be completely empty; its presence tells Python that the directory should be treated as a package. - Executing the Package Import: To use package imports, you must run your script from the root directory of the project rather than from inside the
scriptsfolder. Inmain.py, you would writefrom modules import helper. When running the code from the terminal, navigate to the root folder and runpython -m scripts.main. This allows Python to resolve the package hierarchy correctly. - Verify the Import: Run your
main.pyfile. If you see the output "Hello from the other folder!", the connection between the two directories has been successfully established.
Common Mistakes
One of the most frequent errors is using a relative path in sys.path.append(). While sys.path.append('../modules') might work if you launch the script from a specific folder, it will fail if you run the script from a different working directory. Always use os.path.abspath() or the pathlib module to generate absolute paths, ensuring the script remains portable across different machines.
Another common mistake is forgetting the __init__.py file when attempting to use package-style imports. In older versions of Python, this file was mandatory. While Python 3.3+ introduced implicit namespace packages (which don't strictly require the file), including __init__.py is still a best practice to avoid ambiguity and ensure compatibility with various tools and IDEs.
Many developers also confuse the "Current Working Directory" (CWD) with the "Script Directory." The CWD is where your terminal is located when you type the python command, whereas the script directory is where the .py file actually resides. If you rely on relative imports without understanding this distinction, you will frequently encounter ModuleNotFoundError.
Tips
For larger projects, consider using a virtual environment and installing your own local package in "editable mode." By creating a setup.py or pyproject.toml file in your root directory, you can run pip install -e .. This installs your project into the environment's site-packages as a link, meaning you can import your modules from anywhere in your system without ever having to manipulate sys.path manually.
If you are working with Python 3.4 or newer, use the pathlib module instead of os.path. pathlib provides an object-oriented approach to filesystem paths that is more readable and less prone to errors. For example, from pathlib import Path; path = Path(__file__).resolve().parent.parent / 'modules' is much cleaner than nested os.path.join calls.
When importing only specific functions from a file in another folder, use the from ... import ... syntax. This prevents your namespace from becoming cluttered and makes it clear exactly which tools you are using from the external module, which improves code maintainability and readability for other developers.
Troubleshooting
If you receive a ModuleNotFoundError, the first step is to print the current search path. Add import sys; print(sys.path) to the top of your script. Check if the directory containing your target file is actually listed in the output. If it is not, your sys.path.append() logic is likely pointing to the wrong location.
If the directory is in the path but the error persists, check for naming conflicts. Ensure you haven't named your local file the same as a built-in Python library (e.g., naming your file json.py or math.py). Python may be importing the built-in library instead of your custom file. Rename your file to something unique and try again.
Check for circular imports. This happens when file_a.py imports file_b.py, and file_b.py simultaneously tries to import file_a.py. This creates a loop that Python cannot resolve, often resulting in an AttributeError stating that a module has no member of a certain name, even though the function clearly exists in the code.
Ensure that the file permissions allow Python to read the target folder. On some operating systems, if the folder was created by a different user or an administrator, the Python process may not have the necessary read permissions to access the module, leading to an ImportError.
Frequently Asked Questions
Can I import a file from a completely different drive?
Yes. By using sys.path.append() with the full absolute path (e.g., D:\\my_modules on Windows), Python can import files from any drive or network share the system has access to.
Is using sys.path.append() considered bad practice?
For small scripts or quick prototypes, it is perfectly acceptable. However, for professional production software, it is better to use proper package structures or install the project via pip to maintain a clean and predictable environment.
What is the difference between a module and a package?
A module is a single .py file. A package is a directory containing one or more modules and usually an __init__.py file, allowing for a hierarchical structuring of the code.
Why does my IDE show a warning even though the code runs?
IDEs like PyCharm or VS Code have their own way of indexing files. They may not know you are modifying sys.path at runtime. You can fix this by right-clicking the folder in your IDE and selecting "Mark Directory as Sources Root."
Does the __init__.py file need to contain code?
No, it can be completely empty. Its primary purpose is to signal to Python that the directory should be treated as a package. However, you can use it to initialize package-level variables or simplify imports for the end user.
Can I import a file from a folder that is above my current folder?
Yes. This is known as a parent-directory import. You can achieve this by adding .. to your path logic or using os.path.dirname() multiple times to move up the directory tree before appending the path to sys.path.