Binary File Programs:-
# Menu-Driven Program for List Operations on a Binary File (Movie Collection)
Python Code:
import pickle
import os
import shutil # For backup/restore feature
def initialize_movie_file(file_name):
"""Create the binary file with sample movie data if it doesn't exist."""
if not os.path.exists(file_name):
sample_movies = [
{'title': 'Inception', 'director': 'Christopher Nolan', 'year': 2010},
{'title': 'The Godfather', 'director': 'Francis Ford Coppola', 'year': 1972},
{'title': 'The Dark Knight', 'director': 'Christopher Nolan', 'year': 2008}
with open(file_name, 'wb') as f:
pickle.dump(sample_movies, f)
print(f"Binary file '{file_name}' created with initial movie data.")
def save_to_binary(file_name, movie_list):
"""Save the movie collection to a binary file."""
with open(file_name, 'wb') as f:
pickle.dump(movie_list, f)
print("Movie collection successfully saved to file.")
def load_from_binary(file_name):
"""Load the movie collection from a binary file."""
if not os.path.exists(file_name):
print(f"File '{file_name}' not found. Starting with an empty collection.")
return []
try:
with open(file_name, 'rb') as f:
return pickle.load(f)
except EOFError:
return []
def show_movies(movies):
"""Display all movies in the collection."""
if not movies:
print("The movie collection is currently empty.")
else:
print("\nCurrent Movie Collection:")
for idx, movie in enumerate(movies, start=1):
print(f"{idx}. {movie['title']} (Director: {movie['director']}, Year: {movie['year']})")
def find_movie(movies, movie_title):
"""Find a movie by title and show its position in the collection."""
for idx, movie in enumerate(movies):
if movie['title'].lower() == movie_title.lower():
print(f"Movie '{movie_title}' is at position {idx + 1}.")
return
print(f"Movie '{movie_title}' not found in the collection.")
def modify_movie(movies, pos, new_info):
"""Modify a movie's details."""
if 0 <= pos < len(movies):
movies[pos] = new_info
print(f"Movie updated to: {new_info['title']} (Director: {new_info['director']}, Year: {new_info['year']})")
else:
print("Invalid movie position.")
def remove_movie(movies, pos):
"""Remove a movie from the collection."""
if 0 <= pos < len(movies):
removed_movie = movies.pop(pos)
print(f"Movie '{removed_movie['title']}' has been removed.")
else:
print("Invalid movie position.")
def sort_movies(movies, key):
"""Sort movies by the given key (title, director, or year)."""
if not movies:
print("No movies to sort.")
return movies
sorted_movies = sorted(movies, key=lambda x: x[key].lower() if isinstance(x[key], str) else x[key])
print(f"Movies sorted by {key}.")
return sorted_movies
def count_movies(movies):
"""Display the total number of movies in the collection."""
print(f"Total number of movies: {len(movies)}")
def clear_collection(movies, file_name):
"""Clear the entire movie collection (with confirmation)."""
confirm = input("Are you sure you want to clear the entire collection? (yes/no): ").strip().lower()
if confirm == 'yes':
movies.clear()
save_to_binary(file_name, movies)
print("Movie collection cleared.")
else:
print("Operation canceled.")
def backup_collection(file_name, backup_file):
"""Backup the movie collection to another file."""
try:
shutil.copy(file_name, backup_file)
print(f"Backup created: {backup_file}")
except FileNotFoundError:
print("Original file not found. Backup failed.")
def restore_collection(file_name, backup_file):
"""Restore the movie collection from the backup file."""
try:
shutil.copy(backup_file, file_name)
print(f"Collection restored from backup: {backup_file}")
except FileNotFoundError:
print("Backup file not found. Restore failed.")
def movie_menu():
file_name = 'movie_collection.bin'
backup_file = 'movie_collection_backup.bin' # For backup and restore feature
initialize_movie_file(file_name) # Initialize file with sample data if it doesn't exist
movies = load_from_binary(file_name)
while True:
print("\nMovie Collection Menu:")
print("1. Add a movie")
print("2. View all movies")
print("3. Remove a movie")
print("4. Search for a movie")
print("5. Edit a movie")
print("6. Sort movies")
print("7. Count movies")
print("8. Clear movie collection")
print("9. Backup collection")
print("10. Restore collection from backup")
print("11. Exit")
choice = input("Select an option: ")
if choice == '1':
title = input("Movie Title: ")
director = input("Director: ")
year = input("Year: ")
movies.append({'title': title, 'director': director, 'year': year})
save_to_binary(file_name, movies)
elif choice == '2':
show_movies(movies)
elif choice == '3':
show_movies(movies)
try:
pos = int(input("Movie number to delete: ")) - 1
remove_movie(movies, pos)
save_to_binary(file_name, movies)
except ValueError:
print("Invalid input.")
elif choice == '4':
title = input("Enter movie title to search: ")
find_movie(movies, title)
elif choice == '5':
show_movies(movies)
try:
pos = int(input("Movie number to edit: ")) - 1
new_title = input("New Movie Title: ")
new_director = input("New Director: ")
new_year = input("New Year: ")
modify_movie(movies, pos, {'title': new_title, 'director': new_director, 'year': new_year})
save_to_binary(file_name, movies)
except ValueError:
print("Invalid input.")
elif choice == '6':
key = input("Sort by (title/director/year): ").strip().lower()
if key in ['title', 'director', 'year']:
movies = sort_movies(movies, key)
show_movies(movies)
save_to_binary(file_name, movies)
else:
print("Invalid sort key.")
elif choice == '7':
count_movies(movies)
elif choice == '8':
clear_collection(movies, file_name)
elif choice == '9':
backup_collection(file_name, backup_file)
elif choice == '10':
restore_collection(file_name, backup_file)
elif choice == '11':
print("Exiting the program.")
break
else:
print("Invalid choice.")
if __name__ == "__main__":
movie_menu()
Output:
# Menu-Driven Program for List Operations on a Binary File (Student
Data)
Python Code:
import pickle
import os
def initialize_student_file(file_name):
"""Create the binary file with sample student data if it doesn't exist."""
if not os.path.exists(file_name):
sample_students = {
"001": {"name": "John", "age": 18, "grade": "A"},
"002": {"name": "Sarah", "age": 19, "grade": "B"}
with open(file_name, 'wb') as f:
pickle.dump(sample_students, f)
print(f"Binary file '{file_name}' created with sample student data.")
def save_students(file_name, students):
"""Save the student dictionary to a binary file."""
with open(file_name, 'wb') as f:
pickle.dump(students, f)
print("Student records saved successfully.")
def load_students(file_name):
"""Load the student dictionary from a binary file."""
if not os.path.exists(file_name):
print(f"File '{file_name}' not found. Starting with an empty student collection.")
return {}
try:
with open(file_name, 'rb') as f:
return pickle.load(f)
except EOFError:
return {}
def show_students(students):
"""Display all student records."""
if not students:
print("No students available.")
else:
print("\nCurrent Student List:")
for student_id, details in students.items():
print(f"ID: {student_id} | Name: {details['name']} | Age: {details['age']} | Grade: {details['grade']}")
def delete_student(students, student_id):
"""Remove a student from the collection."""
if student_id in students:
del students[student_id]
print(f"Student with ID '{student_id}' deleted.")
else:
print(f"Student ID '{student_id}' not found.")
def student_menu():
file_name = 'students.bin'
initialize_student_file(file_name)
students = load_students(file_name)
while True:
print("\nStudent Management Menu:")
print("1. Add or Update Student")
print("2. View All Students")
print("3. Delete Student")
print("4. Exit")
choice = input("Select an option: ")
if choice == '1':
student_id = input("Enter Student ID: ")
name = input("Enter Student Name: ")
age = input("Enter Student Age: ")
grade = input("Enter Student Grade: ")
students[student_id] = {'name': name, 'age': age, 'grade': grade}
save_students(file_name, students)
print(f"Student '{student_id}' has been added/updated.")
elif choice == '2':
show_students(students)
elif choice == '3':
student_id = input("Enter Student ID to delete: ")
delete_student(students, student_id)
save_students(file_name, students)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid option. Please try again.")
if __name__ == "__main__":
student_menu()
Output:
C.S.V File Programs:
# C. S.V file program Menu Driven complete program (Library Collection)
Python Code:
import csv
import os
def initialize_csv_file(filename):
"""Initialize the CSV file with sample book data if it doesn't exist."""
if not os.path.exists(filename):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
# Writing the header and some sample data
writer.writerow(["Book ID", "Title", "Author", "Year"])
writer.writerow(["101", "The Great Gatsby", "F. Scott Fitzgerald", "1925"])
writer.writerow(["102", "1984", "George Orwell", "1949"])
print(f"CSV file '{filename}' created with sample data.")
def display_books(filename):
"""Display all records in the CSV file."""
if not os.path.exists(filename):
print("File not found.")
return
with open(filename, 'r') as file:
reader = csv.reader(file)
print("\nLibrary Collection:")
for row in reader:
print(", ".join(row))
def add_book(filename):
"""Add a new book record to the CSV file."""
book_id = input("Enter Book ID: ")
title = input("Enter Book Title: ")
author = input("Enter Author: ")
year = input("Enter Publication Year: ")
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([book_id, title, author, year])
print("Book added successfully.")
def search_book(filename):
"""Search for a book by Book ID."""
book_id_to_search = input("Enter Book ID to search: ")
found = False
if not os.path.exists(filename):
print("File not found.")
return
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[0] == book_id_to_search:
print("Book found: ", ", ".join(row))
found = True
break
if not found:
print(f"Book with ID '{book_id_to_search}' not found.")
def library_menu():
filename = 'library.csv'
initialize_csv_file(filename)
while True:
print("\nLibrary Management Menu:")
print("1. Display all books")
print("2. Add a book")
print("3. Search for a book")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
display_books(filename)
elif choice == '2':
add_book(filename)
elif choice == '3':
search_book(filename)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid option, please try again.")
if __name__ == "__main__":
library_menu()
Output: