简体   繁体   中英

The decryption part of my program doesn't work

I am currently writing a program that encrypts and decrypts text and .txt files, The entire program works fine except for the part that decrypts .txt files. Here is the code for that section of the program.

while True:
    message = int(input('Open file (1) or type message (2)? '))
    if message == 1:
        file = input('What file should be opened? ')
        file = file + '.txt'
        with open(file) as file:
            file = [line.rstrip('\n') for line in file]
        break
    elif message == 2:
        file = input('What was the encrypted message? ')
        break
    else:
        print('Please enter 1 or 2\n')

displacement = int(input('What was the displacement? '))

for i in range(len(file)):
    num = ord(file[i])
    num -= displacement
    letter = chr(num)
    new_message.append(letter)
new_message = ''.join(new_message)
print('\n' + new_message)

The error I'm getting is: 'TypeError: ord() expected a character, but string of length 5 found'. The same piece of code works for encrypting text, why is this different and what is wrong?

Well there is a lot of things wrong with the code. First off, is this a Ceaser Cipher? If so you should specify if the text is being encrypted/decrypted in the UI cause you would have to do this:

if encrypted==False: num -= displacement
else: num+=displacement 

Second, I found for ciphers it's easier to do a different for loop to handle the text like:

for char in text:
    do_stuff
    print char 
    ## etc

Finally, the main problem is how you are reading the text file. You are making a list. You should try doing:

file = file.read()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM