Objective
Develop a Python program to encode the content of a text file into a new file, transforming the text in a way that it is not easily readable without decryption.
Example Python Exercise
Show Python Code
# This program reads a text file, encodes the content using a simple Caesar Cipher,
# and writes the encoded content to a new file.
def encode_text(input_filename, shift=3):
try:
# Open the input file in read mode
with open(input_filename, 'r') as infile:
# Read the content of the file
content = infile.read()
# Initialize the encoded content
encoded_content = ''
# Encode each character in the content
for char in content:
if char.isalpha(): # Check if the character is a letter
# Shift the character and handle both lowercase and uppercase letters
shift_base = 65 if char.isupper() else 97
encoded_char = chr((ord(char) - shift_base + shift) % 26 + shift_base)
encoded_content += encoded_char
else:
# If the character is not a letter, keep it unchanged
encoded_content += char
# Create a new file name by adding ".encoded" extension
output_filename = input_filename + ".encoded"
# Open the output file in write mode
with open(output_filename, 'w') as outfile:
# Write the encoded content to the new file
outfile.write(encoded_content)
print(f"File has been successfully encoded and saved as {output_filename}.")
except FileNotFoundError:
print(f"The file {input_filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
input_file = "example.txt" # Replace with your input file name
encode_text(input_file)
Output
If the example.txt file contains:
Hello, this is a secret message.
After running the program with a shift of 3, the example.txt.encoded file will contain:
Khoor, wklv lv d vhfuhw phvvdjh.
Share this Python Exercise