mary jerson
mary jerson

Reputation: 71

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

Upvotes: 0

Views: 2099

Answers (2)

Leso_KN
Leso_KN

Reputation: 176

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.

Upvotes: 0

xgord
xgord

Reputation: 4796

You actually are getting all the output in the text file. The "problem" is that your cipher is using the full range of all ASCII chars, which includes some non-printable chars.

Example, SOH is the "start of heading" symbol, which doesn't really mean anything visually.

ASCII chart

Upvotes: 1

Related Questions