6 To 10
6 To 10
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)
8.
a) Write a python program to find the whether the given input is palindrome or not (for both string and
integer) using the concept of polymorphism and inheritance.
class PalindromeChecker:
def is_palindrome(self, input_value):
raise NotImplementedError("Subclasses must implement
this method")
class StringPalindrome(PalindromeChecker):
def is_palindrome(self, input_value):
input_value = input_value.lower().replace(" ", "")
# Ignore case and spaces
return input_value == input_value[::-1]
class IntegerPalindrome(PalindromeChecker):
def is_palindrome(self, input_value):
return str(input_value) == str(input_value)[::-1]
if __name__ == "__main__":
input_value = input("Enter a string or an integer: ")
if input_value.isdigit():
checker = IntegerPalindrome()
else:
checker = StringPalindrome()
9
a) Write a python program to download the all XKCD comics
import os
import requests
from IPython.display import Image, display
def download_xkcd_comics(output_folder):
os.makedirs(output_folder, exist_ok=True)
url = 'https://xkcd.com/{}/info.0.json'
comic_number = 1
while True:
response = requests.get(url.format(comic_number))
if response.status_code == 200:
comic_data = response.json()
image_url = comic_data['img']
image_response = requests.get(image_url)
if image_response.status_code == 200:
image_name = os.path.basename(image_url)
image_path = os.path.join(output_folder,
image_name)
comic_number += 1
if __name__ == "__main__":
output_folder = 'xkcd_comics'
download_xkcd_comics(output_folder)
9
b) Demonstrate python program to read the data from the spreadsheet and write the data in to the
spreadsheet
import openpyxl
def read_spreadsheet(file_path):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active
workbook.close()
def write_spreadsheet(file_path):
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet["A1"] = "Name"
sheet["B1"] = "Age"
sheet["C1"] = "City"
data = [
("A", 28, "Bangalore"),
("B", 32, "Mumbai"),
("C", 24, "Delhi")
]
workbook.save(file_path)
workbook.close()
if __name__ == "__main__":
read_file_path = "C:\\Users\\DELL\\data.xlsx"
write_file_path = "C:\\Users\\DELL\\output.xlsx"
10
a) Write a python program to combine select pages from many PDFs
import PyPDF2
output_pdf = 'combined_pages.pdf'
combine_selected_pages(input_pdfs, output_pdf,
selected_pages)
print(f'Selected pages from input PDFs combined and saved as
{output_pdf}')
10 b) Write a python program to fetch current weather data from the JSON file
import json
def fetch_weather_data(file_name):
try:
with open(file_name, 'r') as json_file:
weather_data = json.load(json_file)
return weather_data
except FileNotFoundError:
print(f"Error: File '{file_name}' not found.")
return None
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in
'{file_name}'.")
return None
def display_weather_data(weather_data):
if weather_data is not None:
print("Weather Information:")
print(f"City: {weather_data['city']}")
print(f"Temperature:
{weather_data['temperature']}°F")
print(f"Conditions: {weather_data['conditions']}")