Search code examples
pythonasciiwritetofile

How to write to a txt file ascii characters in python?


I'm implementing a XOR method, and I want to write the ciphered message to a txt file, but in the way I'm doing it, I get strange characters instead of the message.

Here is the code:

from itertools import cycle

msg = 'RUNNINGFAST'
key = 'SADSTORY'

cipher = ''.join(chr(ord(c)^ord(k)) for c,k in zip(msg, cycle(key)))

print('%s ^ %s = %s ' % (msg, key, cipher))
msg = ''.join(chr(ord(c)^ord(k)) for c,k in zip(cipher, cycle(key)))
print('%s ^ %s = %s ' % (cipher, key, msg))

with open("XOR - Msg_Cipher.txt", "w",) as text_file:
    text_file.write("msg: %s \nCipher: %s" % (msg, cipher))

the output looks like this:

enter image description here

the txt file looks like this:

enter image description here

How can I get the output inside the txt file?

Thanks for your help


Solution

  • I think you need to use another text editor. Windows' notepad doesn't render the control characters correctly.

    Try to use Programmers Notepad or Notepad++ for example.