1. import os
  2. import argparse
  3. import base64
  4. def encode_file(input_file, output_file):
  5. """Encodes the content of a file using base64 and writes it to a new file."""
  6. try:
  7. with open(input_file, 'r') as f_in:
  8. file_content = f_in.read().encode('utf-8') # Read file content and encode to bytes
  9. encoded_bytes = base64.b64encode(file_content) # Encode the bytes using base64
  10. encoded_string = encoded_bytes.decode('utf-8') # Decode the bytes to string
  11. with open(output_file, 'w') as f_out:
  12. f_out.write(encoded_string) # Write encoded string to the output file
  13. print(f"File '{input_file}' encoded to '{output_file}'")
  14. except FileNotFoundError:
  15. print(f"Error: File '{input_file}' not found.")
  16. except Exception as e:
  17. print(f"An error occurred: {e}")
  18. def main():
  19. """Parses command line arguments and encodes the specified files."""
  20. parser = argparse.ArgumentParser(description="Encode files using base64.")
  21. parser.add_argument("input_file", help="Path to the input file.")
  22. parser.add_argument("output_file", help="Path to the output file.")
  23. args = parser.parse_args()
  24. encode_file(args.input_file, args.output_file)
  25. if __name__ == "__main__":
  26. main()

Add your comment