1.2 Binary files in python
v Binary files in python: -
- A binary file is a file that stores data in the form of raw bytes (0s and 1s) instead of plain text.
- In Python, binary files store data in a non-text format such as images, audio files, videos, serialized objects, and more.
- Binary files consist of non-human-readable characters and symbols, which require specific programs to access their contents. They are stored as bytes (zeros and ones), but these bytes do not represent ASCII values of characters. Instead, they represent the actual content, such as images, audio, video, compressed files, executable files, etc.
- Since binary files are not human-readable, opening them in a text editor will display random or unreadable symbols, often referred to as “garbage values”. This happens because the computer interprets the binary content as a sequence of bytes without any text encoding.
- It is also difficult to remove errors from binary files, as their contents cannot be directly interpreted by humans.
- Python programs can be used to read and write both text files and binary files efficiently.
1) Writing
Binary files: -
- Writing Binary Files in Python means storing data as raw bytes instead of plain text.
- This is useful when you want to save images, audio, video, or any non-text data without corruption.
- You must provide data in bytes form.
- We use open( ) method with mode:
"wb" → write binary (creates/overwrites file)
"ab" → append binary (adds data to end of
file)
"wb+" → write and read binary
Example: -
output: -
2) Reading
Binary files: -
- Reading Binary Files in Python means loading data as raw bytes from a file instead of interpreting it as text.
- This is used for images, audio, video, executables, compressed files, or any non-text data.
- Use open( ) method with mode:
"rb"
→ read binary
"rb+"
→ read and write binary
Example: -
output: -