Class 12 Programs
- 1.Read text file line by line with # separator
- 2.Count vowels, consonants, uppercase, lowercase in file
- 3.Remove lines containing character 'a'
- 4.Binary file with name and roll number search
- 5.Binary file update marks by roll number
- 6.Random number generator (Dice Simulator)
- 7.Stack implementation using list
- 8.CSV file with user-id and password
- 9.User Defined Functions to manipulate List Store Indices of Non Zero elements &Double the Odd values
- 10.WORKING WITH BINARY FILE IN PYTHON Create a binary file, Search and display the records from the binary file
- 11.TEXT FILES IN PYTHON Remove duplicate lines from the file & Display unique words present in the file
- 12.TEXT FILES IN PYTHON Copying lines to a new file & Replacing the '-' sign with a blankspace
- 13.TEXT FILES IN PYTHON Count the lines starts with I/T & Display the lines with exactly 6 words
- 14.TEXT FILES IN PYTHON Count the occurrences of word & Count number of vowels and consonants
- 15.User Defined Functions to Manipulate List Find the Longest Word and Shifting the elements to left
- 16.IMPLEMENTATION OF STACK USING LIST IN PYTHON
- 17.ALTER table to add new attributes / modify data type / drop attribute
- 18.UPDATE table to modify data
- 19.ORDER By to display data in ascending / descending order
- 20.DELETE to remove tuple(s)
- 21.GROUP BY and find the min, max, sum, count and average
- 22.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - DELETE RECORDS
- 23.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - UPDATE RECORDS
- 24.INTERFACING PYTHON WITH MYSQL DATABASE CONNECTIVITY APPLICATION PROGRAM - INSERT RECORDS
Quick Tips
- • Import random module for number generation
- • Use randint(1, 6) for dice simulation
- • Handle user input validation properly
Binary File Update
AIM
To write a Python program to update specific records in a binary file.
ALGORITHM
- Start
- Import pickle module
- Read all records from the binary file into a list
- Search for the record to be updated
- Modify the required fields of the record
- Write the updated list back to the file
- Display confirmation message
- Stop
PROGRAM
import pickle
def update_record():
try:
# Read all records
records = []
with open('student.dat', 'rb') as file:
try:
while True:
record = pickle.load(file)
records.append(record)
except EOFError:
pass
if not records:
print("No records found!")
return
# Search for record to update
roll_to_update = int(input("Enter roll number to update: "))
found = False
for i, record in enumerate(records):
if record['roll'] == roll_to_update:
print(f"Current record:")
print(f"Name: {record['name']}")
print(f"Roll: {record['roll']}")
print(f"Marks: {record['marks']}")
# Update fields
new_name = input("Enter new name (or press Enter to keep current): ")
new_marks = input("Enter new marks (or press Enter to keep current): ")
if new_name:
records[i]['name'] = new_name
if new_marks:
records[i]['marks'] = int(new_marks)
found = True
break
if not found:
print("Record not found!")
return
# Write updated records back to file
with open('student.dat', 'wb') as file:
for record in records:
pickle.dump(record, file)
print("Record updated successfully!")
except FileNotFoundError:
print("File not found!")
except Exception as e:
print(f"Error: {e}")
def display_records():
try:
with open('student.dat', 'rb') as file:
print("All Records:")
print("=" * 30)
try:
while True:
record = pickle.load(file)
print(f"Name: {record['name']}")
print(f"Roll: {record['roll']}")
print(f"Marks: {record['marks']}")
print("-" * 20)
except EOFError:
pass
except FileNotFoundError:
print("File not found!")
# Main program
if __name__ == "__main__":
choice = input("1. Update record\n2. Display records\nEnter choice: ")
if choice == '1':
update_record()
elif choice == '2':
display_records()
else:
print("Invalid choice!")OUTPUT
1. Update record
2. Display records
Enter choice: 1
Enter roll number to update: 101
Current record:
Name: John Doe
Roll: 101
Marks: 85
Enter new name (or press Enter to keep current): John Smith
Enter new marks (or press Enter to keep current): 90
Record updated successfully!
CONCLUSION
Thus, the program to update records in a binary file was successfully executed and verified.
VIVA QUESTIONS
Why do we need to read all records before updating?
Binary files don't support in-place updates easily. We read all records, modify in memory, then write back.
What are the file modes 'rb' and 'wb'?
'rb' opens file for reading in binary mode, 'wb' opens file for writing in binary mode.