Search code examples
python-3.xunicodepython-unicodevigenere

UnicodeEncodeError when a space is used


I have created a vigenere cipher then encodes and decodes , but in this instance the encoded word is written to a text file and the deocoded section reads the encoded word and decodes it. The problem is that i have an error when i enter spaces in either the message or the keyword ( both of which are converted to ascii and added or taken away ).

I have found the source of the problem [i think] : https://i.sstatic.net/BhyND.jpg [imgur link that shows 2 screenshots of the problem]

I turned the section that reads and writes the encoded word to the text file into a comment and made the encoded word print into the shell, by doing this the code has no problems with encoding with spaces in either the message and the keyword. However when i un-comment them and make the program write the encoded message to the text file it comes up as an error saying " 'charmap' can't encode character ". If anyone could help i would be greatly appretiated!

encode="" # encoded text is saved in this variable
decode="" # decoded text is saved in this variable
encodedTextSaved="" # what the read encoded text from the text file is saved in 
decodedText = "" # When the encoded text is read back in from the file it goes in this variable
from itertools import cycle

def encrypt(message,keyWord): #defines the variable named 'encrypt'
    def encryptLetter(letterKey):
        letter,keyWord=letterKey
        return chr(ord(letter)+ord(keyWord)) # adds the ascii value of letter and the KeyWord togther and converts them to a character 
    keySeq=cycle(keyWord)
    return "".join(map(encryptLetter,zip(message,keySeq)))

def decrypt(message,keyWord): # defines the variable named 'decrypt'
    def decryptLetter(letterKey):
        letter,keyWord=letterKey
        return chr(ord(letter)-ord(keyWord)) # takes away the the ascii value of letter and the KeyWord togther and converts them to a character 
    keySeq=cycle(keyWord)
    return "".join(map(decryptLetter,zip(message,keySeq)))

start = input("Do you want to start this ingenuitive program (y/n): ")
if start == 'y':
    print()    
    while 1==1:
        decision=input('Do you wish to Encrypt(1) or Decrypt(2) a message or Quit(3):  ')
        if decision == '1':
            while 1==1:
                text=input("Enter text message to encode: ")
                if text == '':
                    print()
                    print("Enter Something!")
                    print()
                else: break
            while 1==1:
                keyWord=input("Enter keyword : ").lower()# Enter the message to be encoded / made sure that the input is turned all to lower case
                if keyWord == '':
                    print()
                    print("Enter Something!")
                    print()
                else: break
            encode = encrypt(text, keyWord) # runs the defined encrypt variable with the inputs 'text' and 'keyWord'
            myFile = open('data.txt', 'w')  # This opens the file called 'data.txt' so we can write to it
            myFile.write(encode) #writes the encoded word to the text file named 'data.txt'

            myFile.close
           #print ("encoded word is --> " + encode)



        elif decision == '2':
            myFile = open("data.txt","r")  # This opens the file called 'data.txt' so we can read it
            encodedTextSaved=myFile.readlines()  # This reads the encoded text into the variable encodedTextSaved
            myFile.close()
            decodedText=encodedTextSaved[0]
            while 1==1:
                keyWord=input("Enter keyword : ").lower()# Enter the message to be encoded / made sure that the input is turned all to lower case
                if keyWord == '':
                    print()
                    print("Enter Something!")
                    print()
                else: break
            decode = decrypt(decodedText, keyWord)# runs the defined decrypt variable with the inputs 'decodedText' and 'keyWord'
            print ("the decoded text is > " + decode)
        elif decision == 'no' or 'No': # if the user does not want to carry on then it quits the program
            print("Okay then....Bye")
            break
        elif decision == '3': # if the user chooses option 3 it breaks the while loop and closes the program
            print()
            break
        else: print("Invalid") # if user enters anything that is not what the program asks for it gives the user a second chance as the input is 'invalid'



if start == 'n': # if the user enters 'n' it does not proceed with the code and quits it 
    print()
    print("We hope that you shall use this program again in the not so distant future")

Solution

  • Your encryption is using characters the default encoding for text files does not support. In Python 3, text strings are Unicode, so specify an encoding when writing them to a file. utf8 handles all Unicode characters so is a good choice. Also make sure to call myFile.close (missing parentheses):

    myFile = open('data.txt', 'w',encoding='utf8')
    myFile.write(encode)
    myFile.close()
    

    Specify the same encoding when reading back the data as well:

    myFile = open("data.txt","r",encoding='utf8')