Python Q22-29 print (2)
Python Q22-29 print (2)
Q22. Create a text file and Perform the following operations on the file
a) Open the file and Read the contents from the file.
b) Check if the file exists or not
c) Write the content and display
d) Append the content to the existing file and display it
e) Remove the file
Code:
import os
filename = "example.txt"
# a)
try:
with open(filename, "r") as file:
print("File Contents:\n", file.read())
except FileNotFoundError:
print("File does not exist.")
# b)
if os.path.exists(filename):
print(f"{filename} exists.")
else:
print(f"{filename} does not exist.")
# c)
with open(filename, "w") as file:
file.write("This is a test file created by Pranjal.\n")
print("Content written to file.")
# d)
with open(filename, "a") as file:
file.write("Appending more content to the file.\n")
print("Content appended.")
# e)
os.remove(filename)
print(f"{filename} has been deleted.")
Output:
Page 29
Python Programming MCA-166P 35113704424
Q23.Write a program to copy the contents of one file into a new file.
i. The operations should be performed only if the file exists and user permits to
overwrite the content of the destination file.
ii. Delete the source file once the contents are copied to destination file
Code:
# copy_file.py
import os
import shutil
source_file = "source.txt"
destination_file = "destination.txt"
if os.path.exists(source_file):
choice = input(f"{destination_file} will be overwritten. Continue? (yes/no):
").strip().lower()
if choice == 'yes':
shutil.copy(source_file, destination_file)
print(f"Copied content from {source_file} to {destination_file}.")
os.remove(source_file)
print(f"{source_file} has been deleted.")
else:
print("Operation aborted.")
else:
print("Source file does not exist.")
Output:
Page 30
Python Programming MCA-166P 35113704424
Q24.Create a binary file with roll number, name and marks. Input a roll number and
perform the following operations:
• update the marks.
• Delete the record
• Display the record
• Append the record
• Search the record
Code:
import pickle
import os
filename = "students.dat"
def append_record():
with open(filename, "ab") as file:
record = {'roll_no': 101, 'name': 'Pranjal', 'marks': 90}
pickle.dump(record, file)
print("Record appended.")
def display_records():
try:
with open(filename, "rb") as file:
while True:
try:
record = pickle.load(file)
print(record)
except EOFError:
break
except FileNotFoundError:
print("File not found.")
append_record()
display_records()
Output:
Page 31
Python Programming MCA-166P 35113704424
Code:
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
@staticmethod
def is_square(length, width):
return length == width
Output:
Page 32
Python Programming MCA-166P 35113704424
Q26.You are building a scheduling system and need to calculate future and past dates.
Write a Python program that:
1. Gets the current date and time using datetime.now().
2. Calculates and prints the date 7 days from now.
3. Calculates and prints the date 30 days ago.
4. Asks the user to enter a number of days and then calculates and prints the date that
many days from today.
Code:
current_date = datetime.now()
print("Current Date:", current_date)
Output:
Page 33
Python Programming MCA-166P 35113704424
Code:
class Person:
def __init__(self, name):
self.name = name
def show_name(self):
print("Name:", self.name)
class Job:
def __init__(self, designation):
self.designation = designation
def show_job(self):
print("Designation:", self.designation)
def show_salary(self):
print("Salary:", self.salary)
Output:
Page 34
Python Programming MCA-166P 35113704424
Q28. Write a Python program that demonstrates the use of super() by:
1. Creating a Parent class Vehicle with an __init__() method to initialize brand.
2. Creating a Child class Car that inherits from Vehicle and adds an attribute model.
3. Use super() in Car to call the parent class constructor inside its __init__() method.
4. Create an object of Car and print both brand and model.
Code:
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
def show_details(self):
print("Brand:", self.brand)
print("Model:", self.model)
Output:
Page 35
Python Programming MCA-166P 35113704424
Code:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def show_details(self):
print(f"Employee Name: {self.name}")
print(f"Salary: {self.salary}")
class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary)
self.department = department
def show_details(self):
super().show_details()
print(f"Department: {self.department}")
manager.show_details()
Output:
Page 36