无法将字节连接到str

And*_*Dev 30 python

这被证明是对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()
Run Code Online (Sandbox Code Playgroud)

输出文件如下所示:

test string

然后我收到这个错误:

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
Run Code Online (Sandbox Code Playgroud)

Woo*_*ble 26

subprocess.check_output() 返回一个bytestring.

在Python 3中,unicode(str)对象和bytes对象之间没有隐式转换.如果你知道输出的编码,就可以.decode()它来得到一个字符串,或者你可以把\n你想要添加到bytes与"\n".encode('ascii')


HIS*_*ISI 11

subprocess.check_output()返回字节.

所以你需要将'\n'转换为字节:

 f.write (plaintext + b'\n')
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助