Can't concat bytes to str

Question:

This is proving to be a rough transition over to python. What is going on here?:

f = open( 'myfile', 'a+' )
f.write('test string' + 'n')

key = "pass:hello"
plaintext = subprocess.check_output(['openssl', 'aes-128-cbc', '-d', '-in', test, '-base64', '-pass', key])
print (plaintext)

f.write (plaintext + 'n')
f.close()

The output file looks like:

test string

and then I get this error:

b'decryption successfuln'
Traceback (most recent call last):
  File ".../Project.py", line 36, in <module>
    f.write (plaintext + 'n')
TypeError: can't concat bytes to str
Asked By: AndroidDev

||

Answers:

subprocess.check_output() returns a bytestring.

In Python 3, there’s no implicit conversion between unicode (str) objects and bytes objects. If you know the encoding of the output, you can .decode() it to get a string, or you can turn the n you want to add to bytes with "n".encode('ascii')

Answered By: Wooble

subprocess.check_output() returns bytes.

so you need to convert ‘n’ to bytes as well:

 f.write (plaintext + b'n')

hope this helps

Answered By: HISI

You can convert type of plaintext to string:

f.write(str(plaintext) + 'n')
Answered By: gcs
f.write(plaintext)
f.write("n".encode("utf-8"))
Answered By: Ravi Prakash
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.