Overview
This lecture explains the main operations of binary files (read, write, search, update) using lists, nested lists, and dictionaries, along with the use of pickling, unpickling, and exception handling.
Introduction to Binary Files
- Data in binary files is stored in 0s and 1s (binary language).
- Image, video, audio, etc. files are in binary format.
- Binary files do not require data translation, making them fast and secure.
- Unlike text files, binary files do not have the concept of end of line.
Pickling and Unpickling
- Pickling: Converting a list/dictionary into a byte stream and writing it to a binary file.
- Unpickling: Converting the byte stream from a binary file back into a structure (list/dictionary).
- pickle.dump is used for pickling, and pickle.load is used for unpickling.
Data Operations in Binary Files
- You can use lists, nested lists, or dictionaries.
- Use wb mode to write, rb mode to read, and ab mode to append data in binary files.
- You must load as many times as you dump.
Exception Handling (Try-Except)
- EOFError can occur from pickle.load; handle it with try-except.
- Put file reading code in try, and error message in except.
Binary File Operations
- Write: Take data in list/dictionary and write to file using pickle.dump.
- Read: Read data using pickle.load; read all records with loop and try-except.
- Search: Search record by user input roll number; print if matched, else "record not found".
- Update: Find record, take new value and update; rewrite the entire list/dictionary to the file.
Key Terms & Definitions
- Binary file: A file that stores data in 0s and 1s.
- Pickling: Saving data to a file by converting it into a byte stream.
- Unpickling: Converting a byte stream back into an object.
- pickle.dump: Function to write an object to a binary file.
- pickle.load: Function to read an object from a binary file.
- EOFError: Error that occurs when no data is found at the end of a file.
Action Items / Next Steps
- Write and run practical code on binary files.
- Watch videos on exception handling.
- Study the topic of text files in the next class.