computer code practical
computer code practical
def count_lines_in_file(filename):
lines = file.readlines()
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):
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):
words = file.read().split()
find_longest_word('example.txt')
4. Write a Python program to replace a word in a text file with another word.
content = file.read()
file.write(content)
outfile.write(infile.read() + '\n')
6. Write a Python program to read a text file and display only the lines that contain a specific word.
lines = file.readlines()
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):
content = file.read()
words = content.split()
word_count = {}
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.
lines = infile.readlines()
outfile.write(line)
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).
lines = infile.readlines()
unique_lines = list(dict.fromkeys(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.
lines = infile.readlines()
outfile.write('-----------------------------\n')
for line in lines:
parts = line.strip().split(',')
student_name = parts[0]
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
students_grades = {
'Alice': 85,
'Bob': 78,
'Charlie': 92,
'Diana': 88
pickle.dump(students_grades, 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
students_scores = [
pickle.dump(students_scores, file)
loaded_scores = pickle.load(file)
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
loaded_ids = pickle.load(file)
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
students_details = [
pickle.dump(students_details, file)
loaded_details = pickle.load(file)
import pickle
books = [
{'title': 'The Great Gatsby', 'author': 'F. Scott Fitzgerald', 'year': 1925}
pickle.dump(books, file)
loaded_books = pickle.load(file)
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
pickle.dump(data, file)
loaded_data = pickle.load(file)
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
tasks = [
pickle.dump(tasks, file)
loaded_tasks = pickle.load(file)
print("Tasks List:")
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
attendance = {
pickle.dump(attendance, file)
loaded_attendance = pickle.load(file)
print("Attendance Records:")
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
expenses = {
pickle.dump(expenses, file)
loaded_expenses = pickle.load(file)
print("Monthly Expenses:")
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
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'}
pickle.dump(projects, file)
loaded_projects = pickle.load(file)
print(f"{project}:")
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):
def read_student_scores(filename):
reader = csv.reader(file)
name = row[0]
scores = row[1:]
average = calculate_average(scores)
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
writer = csv.writer(file)
writer.writerow(['Name', 'Salary'])
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):
reader = csv.reader(file)
product_name = row[0]
stock = int(row[2])
if stock == 0:
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
reader = csv.reader(file)
header = next(reader)
rows.append(header)
if row[0] == product_name:
row[1] = new_price
rows.append(row)
writer = csv.writer(file)
writer.writerows(rows)
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
reader = csv.reader(infile)
writer = csv.writer(outfile)
header = next(reader)
writer.writerow(header)
name = row[0]
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
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:
writer.writerow(row)
writer.writerow(row)
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 = {}
reader = csv.reader(file)
book = row[0]
author = row[1]
author_books[author] = []
author_books[author].append(book)
return author_books
author_books = create_author_book_dict('books.csv')
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
def calculate_age(birthdate):
today = datetime.today()
reader = csv.reader(infile)
writer = csv.writer(outfile)
name = row[0]
birthdate = row[1]
age = calculate_age(birthdate)
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
sales_totals = defaultdict(float)
reader = csv.reader(infile)
product = row[0]
amount = float(row[1])
sales_totals[product] += amount
writer = csv.writer(outfile)
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
employee_hours = {}
reader = csv.reader(infile)
name = row[0]
monthly_hours = float(row[1])
yearly_hours = monthly_hours * 12
employee_hours[name] = yearly_hours
writer = csv.writer(outfile)
writer.writerow([name, hours])
calculate_yearly_hours('monthly_hours.csv', 'yearly_hours.csv')