Module 3
1. Develop a Python program to read and print the contents of a text file.
def read_and_print_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
print("File Contents:")
print(content)
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
2. Develop a Python program find the total size of all the files in the given directory.
import os
def get_total_size(directory_path):
total_size = 0
for dirpath, dirnames, filenames in os.walk(directory_path):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
total_size += os.path.getsize(file_path)
print(f"Total Size of all files in '{directory_path}':")
print(total_size)
3. Develop a python program to determine whether the given string is palindrome
or not.
def reverse(string):
string = string[::-1] # string_name[::-1] is a slice operation to reverse string
return string
s =input("Enter String")
print("The original string is : ", end="")
print(s)
rev=reverse(s)
print("The reversed string is : ", end="")
print(rev)
if s==rev:
print(“given string is palindrome”)
else:
print(“given string is not palindrome”)
4. Write a Phon program that repeatedly asks users for their age and a Password
until they provide valid input. [age is in digit and Password in alphabet an digit
only].
5. Develop a program to solve the contents of text file and write the sorted contents
into a separate text file.[ use strip(), len(), list methods sort(), append and file
methods open (), readlines() and write()]
Refer Prog 6 in lab manual
Module 4
1. Develop a program to backing Up a given Folder (Folder in a current working
directory) into a ZIP File by using relevant modules and suitable methods.
import shutil
import os
def backup_folder(folder_name):
# Get the absolute path of the folder
folder_path = os.path.abspath(folder_name)
# Check if the folder exists
if not os.path.exists(folder_path):
print(f"Error: Folder '{folder_name}' not found.")
return
# Create a ZIP file with the folder name
zip_filename = f"{folder_name}_backup.zip"
with shutil.ZipFile(zip_filename, 'w') as zip_file:
# Walk through the folder and add all files and subdirectories to the ZIP file
for foldername, subfolders, filenames in os.walk(folder_path):
for filename in filenames:
file_path = os.path.join(foldername, filename)
zip_file.write(file_path, os.path.relpath(file_path, folder_path))
print("Backup created successfully: “,zip_filename)
except Exception as e:
folder_name = 'your_folder_name'
backup_folder(folder_name)
2. Develop a Python program to traverse the current directory by listing subfolders
and files.
import os
def list_files_and_folders(directory='.'):
# Get the absolute path of the current directory
directory_path = os.path.abspath(directory)
# Check if the directory exists
if not os.path.exists(directory_path):
print(f"Error: Directory '{directory_path}' not found.")
return
# List files and folders
print(f"Listing files and folders in '{directory_path}':")
for item in os.listdir(directory_path):
item_path = os.path.join(directory_path, item)
if os.path.isfile(item_path):
print(f"File: {item}")
elif os.path.isdir(item_path):
print(f"Folder: {item}")
# Call the function to list files and folders in the current directory
list_files_and_folders()
3. Developer program with the function named DivExp which takes two parameters a,
b and returns a values c(c=a/b). Write suitable assertions fora>0 in function DivExp
and rise and exception when b=0 . The developer suitable program which reads two
values from the console and calls a function DivExp.
Refer Prog 8 in lab manual
Module
1. Define a function which takes TWO objects representing complex numbers and
returns new complex number with a addition of two complex numbers.
Refer prog 9 of lab
2. Define a suitable class ‘Complex’ to represent the complex number. Develop a
program to read N (N >=2) complex numbers and to compute the addition of N
complex numbers.
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
return f"{self.real} + {self.imaginary}j"
def add_complex_numbers(complex_numbers):
result = Complex(0, 0)
for number in complex_numbers:
result.real += number.real
result.imaginary += number.imaginary
return result
def read_complex_numbers(n):
complex_numbers = []
for i in range(n):
real = float(input(f"Enter the real part of complex number {i + 1}: "))
imaginary = float(input(f"Enter the imaginary part of complex number {i + 1}: "))
complex_numbers.append(Complex(real, imaginary))
return complex_numbers
# Read the number of complex numbers (N)
N = int(input("Enter the number of complex numbers (N >= 2): "))
while N < 2:
print("Please enter a value of N that is greater than or equal to 2.")
N = int(input("Enter the number of complex numbers (N >= 2): "))
# Read N complex numbers
numbers = read_complex_numbers(N)
# Compute the addition of N complex numbers
result = add_complex_numbers
3. Define the class and object . construct the class called rectangle and initialise it with
height=100, width=200, starting point as(x=0,y=0) write a program to display the
centre point coordinates of a rectangle.
class Rectangle:
def __init__(self, width, height, x=0, y=0):
self.width = width
self.height = height
self.x = x
self.y = y
def calculate_center(self):
center_x = self.x + self.width / 2
center_y = self.y + self.height / 2
return center_x, center_y
# Create an instance of the Rectangle class with initial values
rectangle = Rectangle(width=200, height=100, x=0, y=0)
# Calculate and display the center point coordinates
center_coordinates = rectangle.calculate_center()
print("The center point coordinates of the rectangle are: “,center_coordinates)