TypeError:write()参数必须是str而不是byte,升级到python 3

exc*_*guy 3 python python-3.x

我正在尝试将代码升级到python3。这行遇到了一些麻烦,

output_file = open(working_dir + "E"+str(s)+".txt", "w+")

output_file.write(','.join(headers) + "\n")
Run Code Online (Sandbox Code Playgroud)

并得到这个错误 TypeError: sequence item 0: expected str instance, bytes found

我尝试过的

  output_file.write(b",".join(headers) + b"\n")

TypeError: write() argument must be str, not bytes
Run Code Online (Sandbox Code Playgroud)

香港专业教育学院也尝试decode()在联接上使用,也尝试使用rw+b打开。

如何str在python 3中转换为?

MrF*_*pes 5

EDIT: to read on how to convert bytes to string, follow the link provided by Martijn Pieters in the 'duplicate' tag.

my original suggestion

output_file.write(','.join([str(v) for v in values]) + "\n")
Run Code Online (Sandbox Code Playgroud)

would give for example

values = [b'a', b'b', b'c']
print(','.join([str(v) for v in values]))
# b'a',b'b',b'c'
Run Code Online (Sandbox Code Playgroud)

So despite this works, it might not be desired. If the bytes should be decoded instead, use bytes.decode() (ideally also with the appropriate encoding provided, for example bytes.decode('latin-1'))

values = [b'a', b'b', b'c']
print(','.join([v.decode() for v in values]))
# a,b,c
Run Code Online (Sandbox Code Playgroud)