Handling Binary Files
Binary files are those that are not made up of directly readable characters, such as images, videos, executables, or audio files. To work with them, we use binary file modes ('rb', 'wb', 'ab').
When reading or writing in binary mode, we work with bytes instead of text strings.
# Creating a dummy binary file (e.g., simulating an image)
binary_data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21' # 'Hello World!' in bytes
with open('binary_example.bin', 'wb') as f:
f.write(binary_data)
f.write(b'\x00\x01\x02\x03') # More binary data
# Reading from a binary file
with open('binary_example.bin', 'rb') as f:
read_data = f.read()
print(f"Read binary data: {read_data}")
print(f"Decoded (if it's text): {read_data.decode('utf-8')}") # Attempt to decode if it's text
# Copying an image (example of binary file manipulation)
try:
with open('source_image.jpg', 'rb') as source:
with open('destination_image_copy.jpg', 'wb') as destination:
while True:
chunk = source.read(4096) # Read in chunks of 4KB
if not chunk:
break
destination.write(chunk)
print("Image copied successfully!")
except FileNotFoundError:
print("Error: source_image.jpg not found. Please create one for testing.")
Note: To test the image example, you will need a source_image.jpg file in the same directory.