What's new

Help Help po

Here's the Python program that accomplishes the task you described:

Python:
# First Program to Encrypt Text File

# Dictionary to assign codes to each letter of the alphabet
codes = {
    'A': '%', 'a': '9',
    'B': '@', 'b': '#',
    'C': '&', 'c': '3',
    'D': '$', 'd': '7',
    'E': '!', 'e': '5',
    'F': '^', 'f': '2',
    'G': '*', 'g': '8',
    'H': '?', 'h': '4',
    'I': '+', 'i': '6',
    'J': '-', 'j': '1',
    'K': '=', 'k': '0',
    'L': '_', 'l': '!',
    'M': '~', 'm': '?',
    'N': ']', 'n': '[',
    'O': '{', 'o': '}',
    'P': '|', 'p': '/',
    'Q': '\\', 'q': '<',
    'R': '>', 'r': '.',
    'S': ',', 's': '&',
    'T': ';', 't': ':',
    'U': '"', 'u': "'",
    'V': '`', 'v': '~',
    'W': '(', 'w': ')',
    'X': ']', 'x': '[',
    'Y': '{', 'y': '}',
    'Z': '|', 'z': '/'
}

def encrypt_file(input_file, output_file):
    with open(input_file, 'r') as file:
        text = file.read()
    
    encrypted_text = ''
    for char in text:
        if char in codes:
            encrypted_text += codes[char]
        else:
            encrypted_text += char
    
    with open(output_file, 'w') as file:
        file.write(encrypted_text)

# Encrypting a text file
encrypt_file('input.txt', 'encrypted_output.txt')

# Second Program to Decrypt Encrypted File

def decrypt_file(input_file):
    with open(input_file, 'r') as file:
        encrypted_text = file.read()
    
    decrypted_text = ''
    for char in encrypted_text:
        for key, value in codes.items():
            if char == value:
                decrypted_text += key
                break
        else:
            decrypted_text += char
    
    print(decrypted_text)

# Decrypting the encrypted file and displaying the decrypted contents
decrypt_file('encrypted_output.txt')

In this program:
  • The encrypt_file function reads the contents of the specified input file, encrypts it using the dictionary provided, and writes the encrypted text to the specified output file.
  • The decrypt_file function reads the encrypted text from the specified file, decrypts it using the reverse lookup of the dictionary, and displays the decrypted text on the screen.
  • You can replace the contents of codes dictionary with your own mapping for encryption and decryption. Make sure the encryption and decryption mappings are consistent.
  • Make sure to have an input text file (e.g., input.txt) in the same directory as the script before running it. The encrypted output will be saved to encrypted_output.txt.

Feel free to customize the encryption mapping and test the program with your own input text file.
 

Similar threads

Back
Top