Search code examples
pythonstringencryption

How to keep \n in encrypting with python?


In this simple code when I give it a text file, the program encrypts it and decrypts it afterwards, the question is why the line if ch != '\n' doesn't work and '\n's are all ignored when the file is decrypted?

# Encryption 
file_location = input('Enter the loaction of your text file: ')

def encrypt_file(paragraphs: list):
output = ''

for ph in paragraphs:
    for ch in ph:
        ASCII_of_ch = ord(ch)
        ASCII_of_ch = int((ASCII_of_ch + 5))
        output += chr(ASCII_of_ch)
        
    return output

with open(file_location, 'r+', encoding='UTF-8') as text_file:
    text_paragraphs = text_file.readlines()
    enc_text = encrypt_file(text_paragraphs)

    text_file.seek(0)
    text_file.write(enc_text)
    print('Done!!')



# Decryption
file_location = input('Enter the loaction of your encrypted file: ')

def decrypt_file(text: str):
   output = ''

    for ch in text:
        ASCII_of_ch = ord(ch)
        ASCII_of_ch = int((ASCII_of_ch - 5))
        output += chr(ASCII_of_ch)
        
    return output

with open(file_location, 'r+', encoding='UTF-8') as text_file:
    file_text = text_file.read()
    enc_text = decrypt_file(file_text)

    text_file.seek(0)
    text_file.write(enc_text)
    print('Done!!')

When I write:

Hi

How are you?

What's up?

after decryption it becomes:

Hi How are you? What's up?


Solution

  • You are splitting your file by \n, which means that it will remove all \n's. Also you have a with open block twice in your code for some reason and it's not clear why.

    Here is a more efficient rewrite of your code.

    file_location = input('Enter the location of your text file: ')
    
    with open(file_location, 'r+', encoding='UTF-8') as text_file:
        text = text_file.read()
        output = ""
        for ch in text:
            if ch != "\n":
                ch_ascii = ord(ch)
                output += chr(ch_ascii - 5)
            else:
                output += "\n"
    
    print(output)