0% found this document useful (0 votes)
42 views10 pages

6 To 10

The program contains Python code to perform several file operations - reading the first few lines of a file, finding the frequency of a word, creating ZIP files, combining PDFs, reading/writing spreadsheet data, and fetching weather data from a JSON file.

Uploaded by

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

6 To 10

The program contains Python code to perform several file operations - reading the first few lines of a file, finding the frequency of a word, creating ZIP files, combining PDFs, reading/writing spreadsheet data, and fetching weather data from a JSON file.

Uploaded by

shrinidhi N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

6a.

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!")

def find_word_frequency(file_name, word):


try:
with open(file_name, 'r') as file:
content = file.read()
frequency = content.count(word)
return frequency
except FileNotFoundError:
return "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)

word_to_find = input("Enter the word to find frequency:


")
frequency = find_word_frequency(file_name, word_to_find)
print(f"Frequency of '{word_to_find}' in the file:
{frequency}")

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

def zip_folder(folder_path, output_zip_filename):


with zipfile.ZipFile(output_zip_filename, 'w',
zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path,
folder_path)
zipf.write(file_path, arcname)

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 update_salary_by_department(self, department,


new_salary):
if self.department == department:
self.salary = new_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),
]

for emp in employees:


print(emp)
department_to_update = "HR"
new_salary_for_department = 58000

for emp in employees:

emp.update_salary_by_department(department_to_update,
new_salary_for_department)

print("\nAfter updating salaries:")


for emp in employees:
print(emp)

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]

def check_palindrome(palindrome_checker, input_value):


if palindrome_checker.is_palindrome(input_value):
return f"'{input_value}' is a palindrome."
else:
return f"'{input_value}' is not a palindrome."

if __name__ == "__main__":
input_value = input("Enter a string or an integer: ")

if input_value.isdigit():
checker = IntegerPalindrome()
else:
checker = StringPalindrome()

result = check_palindrome(checker, input_value)


print(result)

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)

with open(image_path, 'wb') as image_file:


image_file.write(image_response.content)
display(Image(filename=image_path))
else:
print(f"Failed to download image for comic
{comic_number}")
else:
break

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

!pip install openpyxl

import openpyxl

def read_spreadsheet(file_path):
workbook = openpyxl.load_workbook(file_path)
sheet = workbook.active

for row in sheet.iter_rows(min_row=2, values_only=True):


name, age, city = row
print(f"Name: {name}, Age: {age}, City: {city}")

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")
]

for row in data:


sheet.append(row)

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"

# Write data to a spreadsheet


write_spreadsheet(write_file_path)
print("Data written to spreadsheet.")

# Read data from a spreadsheet


read_spreadsheet(read_file_path)

10
a) Write a python program to combine select pages from many PDFs

pip install PyPDF2

import PyPDF2

def combine_selected_pages(input_pdfs, output_pdf,


selected_pages):
pdf_writer = PyPDF2.PdfWriter()

for pdf_file, page_numbers in zip(input_pdfs,


selected_pages):
pdf_reader = PyPDF2.PdfReader(pdf_file)
for page_number in page_numbers:
if 1 <= page_number <= len(pdf_reader.pages):
page = pdf_reader.pages[page_number - 1]
pdf_writer.add_page(page)

with open(output_pdf, 'wb') as output_file:


pdf_writer.write(output_file)

# List of input PDFs, corresponding page numbers to select


input_pdfs = ['new.pdf', 'new1.pdf' ]
selected_pages = [[1, 3], [2], [1, 2]]

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']}")

# Fetch weather data from JSON file


file_name = 'js.json'
weather_data = fetch_weather_data(file_name)

# Display weather data


display_weather_data(weather_data)

You might also like