Binary File Handling in Python
- Binary files store data in binary format (0s and 1s) instead of plain text.
- Examples: Images, videos, executables,
.dat,.binfiles.
| Mode | Description |
|---|---|
'rb' |
Read binary file |
'wb' |
Write binary file |
'ab' |
Append binary file |
'r+' |
Read and write binary file |
Writing Data to Binary file
-
Use
pickle.dump()to write Python objects in binary form.
Example:
import pickle
data = {"name": "Ankit", "age": 21}
file = open("data.bin", "wb")
pickle.dump(data, file)
file.close()
Reading Data from Binary File
-
Use
pickle.load()to read data back.
Example:
import pickle
file = open("data.bin", "rb")
data = pickle.load(file)
print(data)
file.close()
Appending Data in Binary File
import pickle
file = open("data.bin", "ab")
pickle.dump(["Python", "File", "Binary"], file)
file.close()
Key Points
- Always open binary files in binary mode (
b). picklemodule is used for serializing (writing) and deserializing (reading).- Don’t try to open binary files in text editor — data will look like garbage.
- Use
try-exceptwithEOFErrorto detect end of file.
