无法将字节转换为s

2024-06-06 12:14:01 发布

您现在位置: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()

输出文件如下所示:

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

Tags: keyintesthellooutputstringcheckpass
3条回答

可以将plaintext的类型转换为字符串:

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

subprocess.check_output()返回bytestring。

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

subprocess.check_output()返回字节。

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

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

希望这有帮助

相关问题 更多 >