Answer: To import files from different folders in Python you can use the sys.path method.
Importing files from different folders is a common requirement, especially when working on large projects with multiple files. Python provides several ways to import files, in this article, let’s explore the different methods to import files from different folders with practical use cases.
Table of Contents:
Methods to Import Files from Different Folders in Python
Following are some commonly used methods for importing files from different folders in Python:
Method 1: Using sys.path.append() in Python
The sys module allows us to modify the system path to import files from directories that are not in the default search path.
Example:
Output:
Explanation:
The sys.path.append() method temporarily adds the given folder path to the Python system path, allowing us to import the required module.
Method 2: Using the os module in Python
The os module allows us to work with the file system. You can use os.path to modify the current directory and then import files from different folders.
Example:
Output:
Explanation:
Here, we use os.chdir() to change the current working directory. After that, Python can import the module as if it were in the current directory. This method makes sure that Python knows exactly where to look for the file.
Method 3: Using the importlib module in Python
The importlib module allows us to import a module dynamically. This is useful if you need to import a module based on a condition or at runtime.
Example:
Output:
Explanation:
The importlib.import_module() allows us to load a module by its name at runtime. This method can be handy when you need to import modules whose names are not known until the program is running.
Method 4: Using absolute and relative imports in Python
Python supports both absolute and relative imports. With absolute imports, you provide the full path to the module. Relative imports allow you to import modules from within the same package or sub-packages.
Example:
Output:
Conclusion
Each method helps retrieve file paths for efficient file handling. The sys.path.append() is useful for temporarily adding folders to the Python path for module imports. os.chdir() changes the working directory. You can choose the appropriate method based on the use cases.