Objectivo
Desarrollar un programa en Python para extraer únicamente los caracteres alfabéticos contenidos en un archivo binario y volcarlos en un archivo aparte. Los caracteres extraídos deben ser aquellos cuyo código ASCII esté entre 32 y 127, o sea igual a 10 (nueva línea) o 13 (retorno de carro).
Ejemplo Ejercicio Python
Mostrar Código Python
# Python program to extract alphabetic characters from a binary file and dump them into a separate file
def extract_alphabetic_characters(input_file_path, output_file_path):
try:
# Open the input binary file in read mode
with open(input_file_path, 'rb') as input_file:
# Open the output text file in write mode
with open(output_file_path, 'w') as output_file:
# Read the binary file byte by byte
byte = input_file.read(1)
# Process each byte
while byte:
# Convert byte to integer (ASCII value)
ascii_value = ord(byte)
# Check if the byte is a printable ASCII character, newline, or carriage return
if (32 <= ascii_value <= 126) or ascii_value in [10, 13]:
# Write the valid character to the output file
output_file.write(byte.decode('ascii', errors='ignore'))
# Read the next byte
byte = input_file.read(1)
print(f"Alphabetic characters have been extracted and saved to '{output_file_path}'.")
except FileNotFoundError:
print(f"Error: The file '{input_file_path}' was not found.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
extract_alphabetic_characters('input_file.bin', 'output_file.txt')
Output
Example Input (input_file.bin):
Hello, World! This is a test.
12345!@#$%^&*()_+[]{}|;:,.<>?/
Some binary content: \x01\x02\x03
Newline character follows:
This is another line.
Example Output (output_file.txt):
Hello, World! This is a test.
12345!@#$%^&*()_+[]{}|;:,.<>?/
Some binary content:
Newline character follows:
This is another line.
Error Scenarios:
File Not Found:
Error: The file 'input_file.bin' was not found.
General Errors:
Error: Error message
Código de Ejemplo copiado
Comparte este ejercicios Python