[英]Python 2 to 3 “TypeError: a bytes-like object is required, not 'str'”
我正在尝试将代码从 Python 版本 2 转换为 3。
错误:“TypeError:需要类似字节的 object,而不是'str”
使用的代码是:
file = sys.argv[1]
if os.path.exists(file):
with open(file,'r') as inputFile:
i = 0
output = BytesIO()
for line in inputFile.readlines():
if (re.search("^[0-9]+\.",line)):
i += 1
replacement = str(i)+'. '
newLine = re.sub('^[0-9]+\.\s*(\[?[0-9]*\]?\s*)*',replacement,line)
output.write(newLine)
else:
output.write(line)
print ("Number of steps:", i)
with open(file,'w') as inputFile:
inputFile.write(output.getvalue())
我意识到这个错误与 object 的类型有关,但我不明白如何解决这个问题。 我将不胜感激任何指导。 谢谢你。
BytesIO
需要字节。 因此,当您执行output.write(x)
时,您需要x
为字节类型。 问题是line
和newLine
都是字符串类型。
您可以通过对它们进行编码将它们转换为字节,但是由于您尝试将output
写入文件,因此最好的解决方案实际上是将BytesIO
更改为StringIO
。 后者不会抱怨line
和newLine
是字符串,并且您将能够调用inputFile.write(output.getvalue())
,这只有在StringIO
是 StringIO 时才有可能。
所以你需要将字符串编码为字节,例如: bytes_like = some_string.encode('utf-8')
现在它应该可以工作了,然后如果你需要一个字符串,解码你的字节,例如string_type = some_bytes.decode('utf-8')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.