0% found this document useful (0 votes)
5 views13 pages

Python File Management and Debugging

This document is an assignment for a B.Tech in Robotics Engineering student, detailing various Python programming tasks related to file organization, debugging, and error handling. It includes Python scripts for copying files, moving images, counting character frequencies, traversing directories, compressing files, and handling exceptions. The assignment is structured into sections with specific questions and corresponding code answers, along with expected outputs.

Uploaded by

eswarsonu888
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Python File Management and Debugging

This document is an assignment for a B.Tech in Robotics Engineering student, detailing various Python programming tasks related to file organization, debugging, and error handling. It includes Python scripts for copying files, moving images, counting character frequencies, traversing directories, compressing files, and handling exceptions. The assignment is structured into sections with specific questions and corresponding code answers, along with expected outputs.

Uploaded by

eswarsonu888
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dr.

APJ ABDUL KALAM SCHOOL OF ENGINEERING


DEPARTMENT OF ENGINEERING

NAME OF STUDENT: Eswar N

ROLL NUMBER: 24BTRE111

BRANCH: [Link] IN ROBOTICS ENGINEERING

COURSE NAME & CODE: PROBLEM SOLVIING WITH PYTHON & 10ABTRE24314

ASSIGNMENT NO: 4

DATE OF ISSUED: 26/10/2025

DATE OF SUBMISSION: 10/11/2025

MAX MARKS: 10

Signature of Student Signature of the course instructor


Module 4: Python - Organizing files and Debugging
Choice Based Assignment – 4
Sec on A: Organizing files
Q1) Write a Python script using the shu l module to copy all .txt files from one folder to another.
Ans1)
Python code:
import os
import shu l

# Step 1: Define source and des na on folders


source_folder = r"C:\Users\ \Documents\Source_folder" #
des na on_folder = r"C:\Users\ \Documents\des na on_folder"

# Create des na on folder if it doesn't exist


[Link](des na on_folder, exist_ok=True)

for file_name in [Link](source_folder):


if file_name.endswith(".txt"): # only copy .txt files
source_path = [Link](source_folder, file_name)
des na on_path = [Link](des na on_folder, file_name)

shu [Link](source_path, des na on_path)


print(f" Copied: {file_name}")

print("\n All .txt files have been successfully copied!")


Output:

Q2) Create a program that moves all image files (e.g., .jpg, .png) from the current directory to a subfolder
named 'images'.

Ans 2)
Current directory:

Python Code:
import os
import shu l
source_folder = r"C:\Users\Rudrik Joshi\OneDrive\Documents\images"

des na on_folder = [Link](source_folder, "images_moved")


[Link](des na on_folder, exist_ok=True)

moved_count = 0

for file_name in [Link](source_folder):


if file_name.lower().endswith((".jpg", ".jpeg", ".png", ".gif")):
source_path = [Link](source_folder, file_name)
des na on_path = [Link](des na on_folder, file_name)
shu [Link](source_path, des na on_path)
print(f"Moved: {file_name}")
moved_count += 1

if moved_count == 0:
print(" No image files found in the source folder.")
else:
print(f"\n {moved_count} image file(s) moved successfully to '{des na on_folder}'!")
New directory:

Output:
Q3) Character Frequency Counter: Input a string and display how many mes each character occurs using a
dic onary.
Ans 3)
Python Code:
# Character Frequency Counter
text = input("Enter a string: ")

frequency = {}

for char in text:


frequency[char] = [Link](char, 0) + 1

print("\nCharacter Frequency:")
for key, value in [Link]():
print(f"'{key}': {value}")

Output:

Q4)
Develop a script that traverses through a directory tree and prints all folder names and file names using
[Link]().
Ans 4)
Python Code:
import os
# Set the root directory you want to start from
root_dir = r"C:\Users\Rudrik Joshi\Documents"

# Traverse the directory tree


for folder_name, subfolders, filenames in [Link](root_dir):

print(f"\n Folder: {folder_name}")

# List subfolders
if subfolders:
print(" Subfolders:")
for sub in subfolders:
print(f" - {sub}")
else:
print(" No subfolders found.")

# List files
if filenames:
print(" Files:")
for file in filenames:
print(f" - {file}")
else:
print(" No files found.")

Output:
Q5) Create a program that compresses all files in a given folder into a ZIP file using the zipfile module.
Ans 5)
Root folder:

Python Code:
import os
import zipfile
folder_to_compress = r"C:\Users\Rudrik Joshi\Documents\images" #

output_zip = r"C:\Users\Rudrik Joshi\Documents\images_backup.zip"

with zipfi[Link](output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:


for root, dirs, files in [Link](folder_to_compress):
for file in files:
file_path = [Link](root, file)
# Add file to ZIP with rela ve path
arcname = [Link](file_path, folder_to_compress)
[Link](file_path, arcname)

print(f" All files from '{folder_to_compress}' compressed successfully into '{output_zip}'")


Output:

A er Output:

Here we see a new ZIP file created as images_backup


Sec on B: Debugging & Error Handling in python
Q6) Write a Python func on that raises a “ValueError” if the input number is nega ve ?
Ans 6)
Python code:
# Func on to check if a number is nega ve
def check_number(num):
if num < 0:
raise ValueError("ValueError: Nega ve numbers are not allowed!")
else:
print(f" The number {num} is valid (non-nega ve).")
try:
number = int(input("Enter a number: "))
check_number(number)
except ValueError as e:
print(e)

Output:

Q7) Create a program that deliberately causes an excep on and prints the full traceback using the traceback
module.
Python Code:
import traceback

try:
# Deliberately cause an excep on (division by zero)
x = 10 / 0

except Excep on as e:

print(" An excep on occurred!")

print("\n Full Traceback:\n")


traceback.print_exc()

Output:

Q8) Write a func on with an asser on to ensure a list is not empty before processing it.
Ans 8)
Python Code:
# Func on to process a list a er checking it's not empty
def process_list(data_list):

assert len(data_list) > 0, " Asser onError: The list is empty!"

print(f" The list is valid. Sum of elements = {sum(data_list)}")


try:
numbers = [10, 20, 30]
process_list(numbers)
empty_list = []
process_list(empty_list)

except Asser onError as e:


print(e)

Output:

Q9) Create a program that logs all user ac ons and errors into a log file using the logging module.
Ans 9)
Python code:
import logging

# Configure logging
[Link]fig(
filename='user_ac [Link]',
level=[Link],
format='%(asc me)s - %(levelname)s - %(message)s'
)

# Define func ons to simulate user ac ons


def perform_ac on(ac on):
try:
[Link](f"User performed ac on: {ac on}")
print(f" Ac on performed: {ac on}")

# Example of an inten onal error


if ac on == "divide by zero":
result = 5 / 0
except Excep on as e:
[Link](f"Error occurred during '{ac on}': {e}")
print(f" Error: {e}")

# Simulate a few ac ons


perform_ac on("login")
perform_ac on("open file")
perform_ac on("divide by zero") # This will trigger an error
perform_ac on("logout")

print("\n All ac ons and errors have been logged in 'user_ac [Link]'")

Output:

Q10) Debugging Prac ce: Write a small program with inten onal logic errors, then use IDLE’s Debugger to
step through and iden fy the problem.
Ans 10)
Python Code:
# Debugging Prac ce Program

# Goal: Find why the output is wrong using IDLE's Debugger


def find_average(numbers):
total = 0
for num in numbers:
total = num
average = total / len(numbers)
return average

def main():
marks = [85, 90, 78, 92, 88]
print("Student marks:", marks)

avg = find_average(marks)
print("Calculated Average:", avg)

# Another logic issue


if avg > 90:
print("Grade: A")
elif avg > 75:
print("Grade: B")
else:
print("Grade: C")

main()

Output:

You might also like