0

So, I wrote encrypted data to txt file.
And I read the line using readline().
But what I get is string type value.

In the text file, it looks like this:

`b'sc\x00\x01\x9eU\x86\x8aV\x8f\xa3\x9f\xf4iD\x9bv\xea\x05\x11\xdeo\xd7 \xef\xb1iK\xc1;\xa5\x02\x9fz@\xe4|\x9b^\xe5\xf9e\xc4\xf30\xaa\xe8\xcc>\xf8a\xfa;"\xfb)\xc7z|\xc9\x9c\x1c\x19\xc1}\x15\xdd_\xfd\x90z\x865\xe9O\xef\xd9\t\x06\x9c'`

(b'~~~~~~')

But, when I read the text file in python and put it in the variable, it looks like this:

'b\'sc\\x00\\x01\\x9eU\\x86\\x8aV\\x8f\\xa3\\x9f\\xf4iD\\x9bv\\xea\\x05\\x11\\xdeo\\xd7 \\xef\\xb1iK\\xc1;\\xa5\\x02\\x9fz@\\xe4|\\x9b^\\xe5\\xf9e\\xc4\\xf30\\xaa\\xe8\\xcc>\\xf8a\\xfa;"\\xfb)\\xc7z|\\xc9\\x9c\\x1c\\x19\\xc1}\\x15\\xdd_\\xfd\\x90z\\x865\\xe9O\\xef\\xd9\\t\\x06\\x9c\'\n'
('b\'~~~~~~\'\n')



Because of that difference, I get an error message:

you cannot use a string because no string encoding will accept all possible characters.


It recognizes that as a string.
How do I read from file and put it in the variable in bytes type?

pavel
  • 26,538
  • 10
  • 45
  • 61
jakads
  • 1
  • 1
  • The text file is ”wrong” IMHO. It seems you've saved the `repr()` form of a `bytes` object into a text file and are now trying to parse that representation back into a `bytes` object. I would save a more common representation of binary data in the text file, for example Base64. Have a look at the `binascii` module in the Python standard library. – BlackJack Jul 23 '14 at 14:14

2 Answers2

0

The problem may not be in the data type. Your data is binary data, and it may contain a newline (\n). In that case readline only reads up to the newline, i.e. only part of the string.

The error message refers to this problem. Unfortunately, readline is not reliable with binary data. You will need to encode the binary data into a string (using, e.g. base64) so that it can be saved in a text file.

For a working example, see: SimpleCrypt Python Error

For an eaxmple of encoding binary data into a string, see: How does one encode and decode a string with Python for use in a URL?

Community
  • 1
  • 1
DrV
  • 22,637
  • 7
  • 60
  • 72
0

What I've been doing is using .decode() when saving a file, and .encode() when loading it, so the text is in the file as a string, and you open it, and read it as bytes.

Edit:

When encrypting:
with open("encrypted.txt", "w+") as file: file.write(encryptedData.decode())

When decrypting:
with open("encrypted.txt", "r") as file: encryptedFile = file.readlines() encryptedFile = [line.encode() for line in encryptedFile]