6ab 7ab
6ab 7ab
Write a python program to accept a file name from the user and perform the
following operations
1. Display the first N line of the file
2. Find the frequency of occurrence of the word accepted from the user in the file
def display_first_N_lines(file_name, N):
try:
with open(file_name, 'r') as file:
for i in range(N):
line = file.readline().strip()
if not line:
break
print(line)
except FileNotFoundError:
print("File not found!")
if __name__ == "__main__":
file_name = input("Enter the file name: ")
N = int(input("Enter the number of lines to display: "))
display_first_N_lines(file_name, N)
to check output
create a text file named "example.txt" with the following content (Make sure both
the Python script and the "sample.txt" file are in the same directory.)
This is an example file.
File contains some lines of text
for demonstrating the Python program.
Let's see how it works!
6b. Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
import os
import zipfile
if __name__ == "__main__":
# Replace this with the path of the folder you want to
zip
folder_to_zip = "C:\\Users\\DELL\\dummy"
# Replace this with the desired name of the output ZIP
file
output_zip_file = "dummy.zip"
zip_folder(folder_to_zip, output_zip_file)
print(f"Folder '{folder_to_zip}' has been zipped to
'{output_zip_file}'")
7. a By using the concept of inheritance write a python program to find the area of
triangle, circle and rectangle.
import math
class Shape:
def area(self):
pass
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
if __name__ == "__main__":
triangle = Triangle(6, 4)
print("Area of Triangle:", triangle.area())
circle = Circle(5)
print("Area of Circle:", circle.area())
rectangle = Rectangle(7, 3)
print("Area of Rectangle:", rectangle.area())
7. b Write a python program by creating a class called Employee to store the details of
Name, Employee_ID, Department and Salary, and implement a method to update
salary of employees belonging to a given department.
class Employee:
def __init__(self, name, employee_id, department,
salary):
self.name = name
self.employee_id = employee_id
self.department = department
self.salary = salary
def __str__(self):
return f"Name: {self.name}, Employee ID:
{self.employee_id}, Department: {self.department}, Salary:
{self.salary}"
if __name__ == "__main__":
employees = [
Employee("A", 1001, "HR", 50000),
Employee("B", 1002, "IT", 60000),
Employee("C", 1003, "HR", 55000),
Employee("D", 1004, "Finance", 70000),
]
emp.update_salary_by_department(department_to_update,
new_salary_for_department)