1.Write a Python program to count the number of lines in a text file.
def count_lines_in_file(filename):
with open(filename, 'r') as file:
lines = file.readlines()
print(f"Number of lines: {len(lines)}")
count_lines_in_file('example.txt')
2.Write a Python program to read each line from a text file and store it in a list.
def read_lines_into_list(filename):
with open(filename, 'r') as file:
lines = [line.strip() for line in file]
return lines
lines_list = read_lines_into_list('example.txt')
print(lines_list)
3. Write a Python program to find and display the longest word in a text file.
def find_longest_word(filename):
with open(filename, 'r') as file:
words = file.read().split()
longest_word = max(words, key=len)
print(f"Longest word: {longest_word}")
find_longest_word('example.txt')
4. Write a Python program to replace a word in a text file with another word.
def replace_word_in_file(filename, old_word, new_word):
with open(filename, 'r') as file:
content = file.read()
content = content.replace(old_word, new_word)
with open(filename, 'w') as file:
file.write(content)
replace_word_in_file('example.txt', 'oldWord', 'newWord')
5. Write a Python program to merge the contents of two text files into a third file.
def merge_files(file1, file2, output_file):
with open(output_file, 'w') as outfile:
for filename in [file1, file2]:
with open(filename, 'r') as infile:
outfile.write(infile.read() + '\n')
merge_files('file1.txt', 'file2.txt', 'merged.txt')
6. Write a Python program to read a text file and display only the lines that contain a specific word.
def display_lines_with_word(filename, word):
with open(filename, 'r') as file:
lines = file.readlines()
for line in lines:
if word in line:
print(line.strip())
display_lines_with_word('example.txt', 'specificWord')
7. Write a Python program to read a text file and create a dictionary where the keys are the words and the
values are the counts of each word's occurrences.
def word_count_dictionary(filename):
with open(filename, 'r') as file:
content = file.read()
words = content.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
return word_count
word_counts = word_count_dictionary('example.txt')
print(word_counts)
8. Write a Python program to read a text file, remove all the lines that contain a specific word, and save the
result to a new file.
def remove_lines_with_word(input_filename, output_filename, word):
with open(input_filename, 'r') as infile:
lines = infile.readlines()
with open(output_filename, 'w') as outfile:
for line in lines:
if word not in line:
outfile.write(line)
remove_lines_with_word('example.txt', 'filtered.txt', 'removeWord')
9. Write a Python program to read a text file and generate a new file that contains only the unique lines from
the original file (ignoring duplicates).
def remove_duplicate_lines(input_filename, output_filename):
with open(input_filename, 'r') as infile:
lines = infile.readlines()
unique_lines = list(dict.fromkeys(lines))
with open(output_filename, 'w') as outfile:
for line in unique_lines:
outfile.write(line)
remove_duplicate_lines('example.txt', 'unique_lines.txt')
10. Write a Python program that reads a text file of students' names and grades, calculates each student's
average grade, and writes the results (including whether they passed or failed) to a new file.
def calculate_student_averages(input_filename, output_filename):
with open(input_filename, 'r') as infile:
lines = infile.readlines()
with open(output_filename, 'w') as outfile:
outfile.write('Student, Average Grade, Status\n')
outfile.write('-----------------------------\n')
for line in lines:
parts = line.strip().split(',')
student_name = parts[0]
grades = list(map(int, parts[1:]))
average_grade = sum(grades) / len(grades)
status = 'Passed' if average_grade >= 60 else 'Failed'
outfile.write(f'{student_name}, {average_grade:.2f}, {status}\n')
calculate_student_averages('students_grades.txt', 'students_results.txt')
BINARY
1.Write a Python program to store a dictionary containing student names and their grades in a binary file and
then retrieve and print the data.
import pickle
# Dictionary of students and their grades
students_grades = {
'Alice': 85,
'Bob': 78,
'Charlie': 92,
'Diana': 88
# Write the dictionary to a binary file
with open('students_grades.bin', 'wb') as file:
pickle.dump(students_grades, file)
# Read the dictionary back from the binary file
with open('students_grades.bin', 'rb') as file:
loaded_grades = pickle.load(file)
print("Students and their grades:", loaded_grades)
2. Write a Python program to create a list of tuples where each tuple contains a student’s name and a list of
their scores. Store this list in a binary file and then read and display the contents.
import pickle
# List of tuples with student names and their scores
students_scores = [
('Alice', [85, 90, 78]),
('Bob', [72, 88, 91]),
('Charlie', [90, 95, 85]),
('Diana', [88, 76, 92])
# Write the list of tuples to a binary file
with open('students_scores.bin', 'wb') as file:
pickle.dump(students_scores, file)
# Read the list of tuples back from the binary file
with open('students_scores.bin', 'rb') as file:
loaded_scores = pickle.load(file)
print("Students and their scores:", loaded_scores)
3. Write a Python program to store a set of unique student IDs in a binary file and then retrieve and print the
set.
import pickle
# Set of unique student IDs
student_ids = {101, 102, 103, 104, 105}
# Write the set to a binary file
with open('student_ids.bin', 'wb') as file:
pickle.dump(student_ids, file)
# Read the set back from the binary file
with open('student_ids.bin', 'rb') as file:
loaded_ids = pickle.load(file)
print("Set of student IDs:", loaded_ids)
4. Write a Python program to store a list of dictionaries where each dictionary contains a student’s name, age,
and grade. Save this list to a binary file and then read and display the data.
import pickle
# List of dictionaries with student details
students_details = [
{'name': 'Alice', 'age': 16, 'grade': 'A'},
{'name': 'Bob', 'age': 17, 'grade': 'B'},
{'name': 'Charlie', 'age': 16, 'grade': 'A'},
{'name': 'Diana', 'age': 17, 'grade': 'B'}
# Write the list of dictionaries to a binary file
with open('students_details.bin', 'wb') as file:
pickle.dump(students_details, file)
# Read the list of dictionaries back from the binary file
with open('students_details.bin', 'rb') as file:
loaded_details = pickle.load(file)
print("Student details:", loaded_details)
5. Write a Python program to store a list of books where each book is represented as a dictionary with keys for
title, author, and year. Save this list to a binary file and then read and display the data.
import pickle
# List of books represented as dictionaries
books = [
{'title': 'To Kill a Mockingbird', 'author': 'Harper Lee', 'year': 1960},
{'title': '1984', 'author': 'George Orwell', 'year': 1949},
{'title': 'Moby Dick', 'author': 'Herman Melville', 'year': 1851},
{'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'year': 1925}
# Write the list of books to a binary file
with open('books.bin', 'wb') as file:
pickle.dump(books, file)
# Read the list of books back from the binary file
with open('books.bin', 'rb') as file:
loaded_books = pickle.load(file)
print("Books in the library:", loaded_books)
6. Write a Python program to store multiple lists of different items (e.g., a list of student names, a list of grades,
and a list of subjects) in a binary file and then retrieve and display the lists.
import pickle
# Multiple lists of different items
student_names = ['Alice', 'Bob', 'Charlie', 'Diana']
grades = ['A', 'B', 'A', 'B']
subjects = ['Math', 'Science', 'English']
# Store the lists in a tuple
data = (student_names, grades, subjects)
# Write the tuple of lists to a binary file
with open('school_data.bin', 'wb') as file:
pickle.dump(data, file)
# Read the tuple of lists back from the binary file
with open('school_data.bin', 'rb') as file:
loaded_data = pickle.load(file)
print("Student names:", loaded_data[0])
print("Grades:", loaded_data[1])
print("Subjects:", loaded_data[2])
7. Write a Python program to store a list of tasks where each task is represented as a dictionary containing a
task name, due date, and priority level. Save this list to a binary file and then retrieve and display the tasks.
import pickle
# List of tasks, each task is a dictionary
tasks = [
{'Task': 'Complete homework', 'Due Date': '2024-09-15', 'Priority': 'High'},
{'Task': 'Read chapter 5', 'Due Date': '2024-09-10', 'Priority': 'Medium'},
{'Task': 'Buy groceries', 'Due Date': '2024-09-07', 'Priority': 'Low'},
{'Task': 'Prepare presentation', 'Due Date': '2024-09-12', 'Priority': 'High'}
# Write the list of tasks to a binary file
with open('tasks.bin', 'wb') as file:
pickle.dump(tasks, file)
# Read the list of tasks back from the binary file
with open('tasks.bin', 'rb') as file:
loaded_tasks = pickle.load(file)
print("Tasks List:")
for task in loaded_tasks:
print(f"Task: {task['Task']}, Due Date: {task['Due Date']}, Priority: {task['Priority']}")
8. Write a Python program to store a dictionary of student attendance where each student’s name is the key
and the value is a list of boolean values representing their attendance over a week (True for present, False for
absent). Save this data to a binary file and then retrieve and display the attendance records.
import pickle
# Dictionary of student attendance over a week
attendance = {
'Alice': [True, True, False, True, True],
'Bob': [True, False, True, False, True],
'Charlie': [True, True, True, True, True],
'Diana': [False, True, False, True, False]
# Write the attendance dictionary to a binary file
with open('attendance.bin', 'wb') as file:
pickle.dump(attendance, file)
# Read the attendance dictionary back from the binary file
with open('attendance.bin', 'rb') as file:
loaded_attendance = pickle.load(file)
print("Attendance Records:")
for student, days in loaded_attendance.items():
print(f"{student}: {['Present' if day else 'Absent' for day in days]}")
9. Write a Python program to store a dictionary of monthly expenses where the key is the month and the value
is a list of expenses for that month. Save this data to a binary file and then retrieve and display the expenses.
import pickle
# Dictionary of monthly expenses
expenses = {
'January': [200, 150, 300],
'February': [250, 180, 220],
'March': [230, 170, 310],
'April': [240, 200, 260]
# Write the expenses dictionary to a binary file
with open('expenses.bin', 'wb') as file:
pickle.dump(expenses, file)
# Read the expenses dictionary back from the binary file
with open('expenses.bin', 'rb') as file:
loaded_expenses = pickle.load(file)
print("Monthly Expenses:")
for month, expense_list in loaded_expenses.items():
print(f"{month}: {expense_list}")
10. Write a Python program to store a nested dictionary where the outer dictionary's keys are project names
and the values are dictionaries with task names as keys and task statuses (Completed/Incomplete) as values.
Save this data to a binary file and then retrieve and display the project tasks and statuses.
import pickle
# Nested dictionary of project tasks and their statuses
projects = {
'Project Alpha': {'Task 1': 'Completed', 'Task 2': 'Incomplete', 'Task 3': 'Completed'},
'Project Beta': {'Task 1': 'Incomplete', 'Task 2': 'Incomplete', 'Task 3': 'Completed'},
'Project Gamma': {'Task 1': 'Completed', 'Task 2': 'Completed', 'Task 3': 'Incomplete'}
# Write the nested dictionary to a binary file
with open('projects.bin', 'wb') as file:
pickle.dump(projects, file)
# Read the nested dictionary back from the binary file
with open('projects.bin', 'rb') as file:
loaded_projects = pickle.load(file)
print("Project Tasks and Statuses:")
for project, tasks in loaded_projects.items():
print(f"{project}:")
for task, status in tasks.items():
print(f" {task}: {status}")
CSV
1: Write a Python program that reads a CSV file containing student names and scores, and prints each student's
name and their average score.
import csv
def calculate_average(scores):
scores = list(map(float, scores))
return sum(scores) / len(scores)
def read_student_scores(filename):
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
name = row[0]
scores = row[1:]
average = calculate_average(scores)
print(f"Student: {name}, Average Score: {average:.2f}")
read_student_scores('students_scores.csv')
2: Write a Python program that writes a list of employee names and their salaries to a CSV file.
import csv
def write_employee_data(filename, employees):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Salary'])
for name, salary in employees:
writer.writerow([name, salary])
employees = [('John Doe', 50000), ('Jane Smith', 60000), ('Alice Johnson', 55000)]
write_employee_data('employee_salaries.csv', employees)
3: Write a Python program that reads a CSV file of product information and prints products that are out of
stock.
import csv
def check_stock(filename):
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
product_name = row[0]
stock = int(row[2])
if stock == 0:
print(f"Out of stock: {product_name}")
check_stock('products.csv')
4: Write a Python program that updates the price of a specific product in a CSV file and saves the changes.
import csv
def update_product_price(filename, product_name, new_price):
rows = []
with open(filename, 'r') as file:
reader = csv.reader(file)
header = next(reader)
rows.append(header)
for row in reader:
if row[0] == product_name:
row[1] = new_price
rows.append(row)
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
update_product_price('products.csv', 'Widget', '19.99')
5: Write a Python program that reads a CSV file containing student names and scores, and writes a new CSV file
with students who scored above a specified threshold.
import csv
def filter_high_scores(input_filename, output_filename, threshold):
with open(input_filename, 'r') as infile, open(output_filename, 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
header = next(reader)
writer.writerow(header)
for row in reader:
name = row[0]
scores = list(map(float, row[1:]))
average = sum(scores) / len(scores)
if average > threshold:
writer.writerow(row)
filter_high_scores('students_scores.csv', 'high_scorers.csv', 85)
6: Write a Python program that merges two CSV files with similar structures into one.
import csv
def merge_csv_files(file1, file2, output_file):
with open(file1, 'r') as f1, open(file2, 'r') as f2, open(output_file, 'w', newline='') as outfile:
reader1 = csv.reader(f1)
reader2 = csv.reader(f2)
writer = csv.writer(outfile)
header1 = next(reader1)
header2 = next(reader2)
if header1 == header2:
writer.writerow(header1)
else:
raise ValueError("CSV headers do not match")
for row in reader1:
writer.writerow(row)
for row in reader2:
writer.writerow(row)
merge_csv_files('file1.csv', 'file2.csv', 'merged.csv')
7: Write a Python program that reads a CSV file of books and their authors and creates a dictionary where the
authors are the keys and the list of their books are the values.
import csv
def create_author_book_dict(filename):
author_books = {}
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
book = row[0]
author = row[1]
if author not in author_books:
author_books[author] = []
author_books[author].append(book)
return author_books
author_books = create_author_book_dict('books.csv')
for author, books in author_books.items():
print(f"Author: {author}, Books: {', '.join(books)}")
8: Write a Python program that reads a CSV file containing names and birthdates and calculates the age of each
person. Write the results to a new CSV file.
import csv
from datetime import datetime
def calculate_age(birthdate):
today = datetime.today()
birthdate = datetime.strptime(birthdate, '%Y-%m-%d')
return today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
def process_birthdates(input_filename, output_filename):
with open(input_filename, 'r') as infile, open(output_filename, 'w', newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
writer.writerow(['Name', 'Birthdate', 'Age'])
next(reader) # Skip header
for row in reader:
name = row[0]
birthdate = row[1]
age = calculate_age(birthdate)
writer.writerow([name, birthdate, age])
process_birthdates('birthdates.csv', 'ages.csv')
9: Write a Python program that reads a CSV file with sales data and calculates the total sales for each product.
Write the results to a new CSV file.
import csv
from collections import defaultdict
def calculate_total_sales(input_filename, output_filename):
sales_totals = defaultdict(float)
with open(input_filename, 'r') as infile:
reader = csv.reader(infile)
next(reader) # Skip header
for row in reader:
product = row[0]
amount = float(row[1])
sales_totals[product] += amount
with open(output_filename, 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(['Product', 'Total Sales'])
for product, total in sales_totals.items():
writer.writerow([product, total])
calculate_total_sales('sales.csv', 'total_sales.csv')
10: Write a Python program that reads a CSV file containing employee names and their monthly hours worked,
and calculates the total hours worked by each employee for the year (assuming 12 months). Write the results
to a new CSV file.
import csv
def calculate_yearly_hours(input_filename, output_filename):
employee_hours = {}
with open(input_filename, 'r') as infile:
reader = csv.reader(infile)
next(reader) # Skip header
for row in reader:
name = row[0]
monthly_hours = float(row[1])
yearly_hours = monthly_hours * 12
employee_hours[name] = yearly_hours
with open(output_filename, 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(['Employee Name', 'Yearly Hours'])
for name, hours in employee_hours.items():
writer.writerow([name, hours])
calculate_yearly_hours('monthly_hours.csv', 'yearly_hours.csv')