无法将字节串连接到字符串

48

这证明转向Python是一个艰难的过程。这里发生了什么?:

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()

输出文件看起来像这样:
测试字符串
然后我得到了这个错误:
b'decryption successful\n'
Traceback (most recent call last):
  File ".../Project.py", line 36, in <module>
    f.write (plaintext + '\n')
TypeError: can't concat bytes to str

1
解码您的明文或编码换行符。 - Hyperboreus
4个回答

48

subprocess.check_output() 返回一个字节字符串。

在 Python 3 中,unicodestr)对象和 bytes 对象之间没有隐式转换。如果您知道输出的编码方式,您可以使用 .decode() 来获取字符串,或者您可以使用 "\n".encode('ascii') 将要添加的 \n 转换为 bytes


15

subprocess.check_output() 返回字节。

因此,您也需要将'\n'转换为字节:

 f.write (plaintext + b'\n')

希望这能帮到你


2
你可以将plaintext的类型转换为字符串:最初的回答。
f.write(str(plaintext) + '\n')

在 [answer] 上,您可以找到更多有关良好格式答案的信息。尽管您的答案可能是正确的,但它相当简短。 - Stef Geysels

1
f.write(plaintext)
f.write("\n".encode("utf-8"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接