Manejo de Archivos Binarios
Los archivos binarios son aquellos que no están compuestos por caracteres legibles directamente, como imágenes, videos, ejecutables o archivos de audio. Para trabajar con ellos, usamos los modos de apertura binarios ('rb', 'wb', 'ab').
Cuando leemos o escribimos en modo binario, no trabajamos con cadenas de texto, sino con bytes.
# 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.")
Nota: Para probar el ejemplo de la imagen, necesitarás tener un archivo source_image.jpg en el mismo directorio.