Encrypting text files

Using simple file handling, we can easily use any cipher to encrypt and decrypt text files. The script below encrypts the contents of plaintext.txt and writes them to encrypted.txt, and then it decrypts the contents of encrypted.txt and writes the output to decrypted.txt.


from caesar import caesar # get this file from here
CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # this string can contain other characters like !, @, etc.

def process_file(input_file, output_file, key, mode):
    with open(input_file, "r") as file:
        text = file.read()

    message = ""
    if mode == "encrypt":
        processed_text = caesar(text, key, "encrypt")
        message = f"File '{input_file}' encrypted to '{output_file}' with key {key}."
    elif mode == "decrypt":
        processed_text = caesar(text, key, "decrypt")
        message = f"File '{input_file}' decrypted to '{output_file}' with key {key}."

    with open(output_file, "w") as file:
        file.write(processed_text)

key = 13
process_file("plaintext.txt", "encrypted.txt", key, "encrypt")
process_file("encrypted.txt", "decrypted.txt", key, "decrypt")