Python 2到3“ TypeError:需要一个类似字节的对象,而不是'str'”

卡尔提克

我正在尝试将代码从Python版本2转换为3。

错误:“ TypeError:需要一个类似字节的对象,而不是'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())

我意识到该错误与对象的类型有关,但我不知道如何解决该问题。我将不胜感激。谢谢。

to

BytesIO期望字节。因此,当您执行时output.write(x),您必须x是字节类型。问题在于两者linenewLine均为字符串类型。

您可以通过编码它们将它们转换为字节,但因为你试图写入output到文件中,最好的解决办法实际上是改变到BytesIOStringIO后者不会抱怨linenewLine成为字符串,并且您可以调用inputFile.write(output.getvalue()),只有在output为a时才有可能StringIO

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python 3-TypeError:需要一个类似字节的对象,而不是'str'

Python3 TypeError:需要一个类似字节的对象,而不是“str”

Python3 .replace产生TypeError:需要一个类似字节的对象,而不是'str'

Python 3,TypeError:需要一个类似字节的对象,而不是'str'

TypeError:需要一个类似字节的对象,而在Python 3中打开Python 2 Pickle文件时不是'str'

TypeError:在Python3中写入文件时需要一个类似字节的对象,而不是'str'

Python3写入gzip文件-memoryview:需要一个类似字节的对象,而不是'str'

Python 3 升级,需要一个类似字节的对象,而不是“str”

使用Python 3.5,抛出错误:TypeError:需要一个类似字节的对象,而不是'str'

TypeError:需要一个类似字节的对象,而不是'str'–用Python保存JSON数据

Python 3.7 TypeError:需要一个类似字节的对象,而不是'str'

python 3.5:“ TypeError:memoryview:需要一个类似字节的对象,而不是'str'”

TypeError:需要一个类似字节的对象,而在python和CSV中不是'str'

TypeError:需要一个类似字节的对象,而在python和CSV中不是'str'

Python错误:TypeError:需要一个类似字节的对象,而不是'str'

类型错误:需要一个类似字节的对象,而不是无服务器和 Python3 的“str”

Python 3.5 TypeError:需要一个类似字节的对象,而不是使用truncate过滤器的'str'

Python 3.6:TypeError:在尝试打印页面中的所有链接时,需要一个类似字节的对象,而不是'str'

TypeError:在Python 3.5.1中使用REST时需要一个类似字节的对象,而不是'str'

需要一个类似字节的对象,而不是python中的“ str”错误

Python2 到 Python3 的转换?类型错误:内存视图:需要类似字节的对象,而不是“str”

使用python计算excel中的重复行,并且我收到错误TypeError:需要一个类似字节的对象,而不是'str'

类型错误:需要一个类似字节的对象,而不是“int”python3

Python:需要一个类似字节的对象,打印时不需要'str'

需要一个类似字节的对象,而不是'str'

错误:需要一个类似字节的对象,而不是'str'

python3:类型错误:需要类似字节的对象,而不是“str”

TypeError:需要一个类似字节的对象,而不是'str''xxx';'xxx'

如何解决Json错误:TypeError:需要一个类似字节的对象,而不是'str'