Program12
12. Develop a program to display contents of a folder recursively (Directory) having sub-folders and files (name and type).
Objective of the Program
To understand directory handling
To use
osmoduleTo apply recursion
To differentiate between files and folders
To display hierarchical structure
Logical Construction (Think Before You Code)
Suppose we have this folder:
MyFolder/
│
├── file1.txt
├── file2.py
│
├── SubFolder1/
│ ├── file3.doc
│
└── SubFolder2/
├── file4.jpg
How to Solve?
Read folder path from user
Use
os.listdir()to get contentsFor each item:
If item is file → print as File
If item is directory → print as Directory
Call function again (recursively)
👉 Key Idea:
If item is directory → call same function again.
This is called Recursion.
Flowchart (Block Diagram of Logic)
Flowchart Explanation
Start
Read folder path
List contents
For each item:
If file → print
If directory → print
Call function recursively
Stop
Algorithm
Start
Define function
display_folder(path)Get list of contents using
os.listdir()For each item in list:
Join path using
os.path.join()If item is file → print name and type
If item is directory →
Print name and type
Call
display_folder()again
Read folder path
Call function
Stop
Python Program
⚠ Students must complete missing parts.
# Program to display folder contents recursively
import os
def display_folder(path):
items = os.____________(path)
for item in items:
full_path = os.path.____________(path, item)
if os.path.____________(full_path):
print("File:", item)
elif os.path.____________(full_path):
print("Directory:", item)
display_folder(____________)
folder_path = input("Enter folder path: ")
if os.path.exists(folder_path):
display_folder(folder_path)
else:
print("Invalid folder path")
Probable Output
Important Concepts Used
osmoduleos.listdir()os.path.join()os.path.isfile()os.path.isdir()Recursion
Path validation
Viva Voce Questions
What is recursion?
Why do we use
os.path.join()?Difference between file and directory?
What is base condition in recursion?
What happens if folder contains many nested folders?
What is difference between listdir() and walk()?
Can we do this without recursion?
Procedure to Execute the Program
Create some folders and subfolders
Add sample files
Run the program
Enter folder path
Observe output
Google Colab – Online Execution
👉 Click the link below to run the complete working version of this program online:
[https://colab.research.google.com/drive/1vr21YSqZRTfZ0Ie2HNalA4oLkqL8Hl05?usp=sharing]
Program Explanation
Assignment for Students
Display file size
Count total number of files
Count total number of directories
Implement using
os.walk()Display file extension separately

Comments
Post a Comment