Sunday, March 19, 2023

Can we use the path from parent folder to include a module in the current python file if the module is in the same directory as the current file

Yes, you can use the dot notation to specify the path to module.py relative to the parent folder of the current file by writing from parent_folder.subfolder import module.

Here's an example:

javascript
parent_folder/ subfolder/ module.py current_file.py

In current_file.py, you can import module.py by using the following code:

python
from parent_folder.subfolder import module

This assumes that the parent_folder is in the Python path. You can add the parent_folder to the Python path by appending it to sys.path:

python
import sys sys.path.append('path/to/parent_folder') from parent_folder.subfolder import module

Note that it's generally recommended to use absolute paths or to add the root folder of your project to the Python path, as using relative paths can make your code less portable.

No comments:

Post a Comment