DEV Community

Cover image for Importing FilesπŸ“ from different FolderπŸ—ƒοΈ
AYON KARMAKAR
AYON KARMAKAR

Posted on • Edited on

Importing FilesπŸ“ from different FolderπŸ—ƒοΈ

Folder structure

GitHub Repo Practical project

Folders
β”œβ”€β”€ Folder1
β”‚   β”œβ”€β”€ subFolder1
β”‚   β”‚    └── File2.py 
β”‚   β”œβ”€β”€ File1.py  
β”‚   └── MainFile.py 
└── Folder2
    └── subFolder3
         └── File3.py
Enter fullscreen mode Exit fullscreen mode

Main Folder is Folders
Folders -> contains 2 subFolder Name Folder1 & Folder2
Folder1 -> subFolder1 & MainFile.py
Folder2 -> subFolder3 -> File3.py
subFolder1 -> File1.py & File2.py

To import File from different Folders

1. File in the same directory

MainFile.py

import File1
Enter fullscreen mode Exit fullscreen mode

2. File in the sub directory

MainFile.py

from subFolder1 import File2
Enter fullscreen mode Exit fullscreen mode

3. File in the 1 step back parent directory

File2.py

from ..MainFile import ClassName
Enter fullscreen mode Exit fullscreen mode

4. File in the parent directory

MainFile.py

# You Can use this to import file from any directory
import sys
sys.path.insert(1,'C://Repo//temptodel//Folders//Folder2//subFolder3')

import File3
print(File3.f33)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)