python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python TypeError: an integer is required (got type str)

解决Python TypeError: an integer is required (got type str)问题及过程

作者:Bug 挖掘机

在Python3中打开文件时,如果遇到TypeError: an integer is required (got type str),通常是因为open函数的第三个参数被误认为是编码方式,本文详细解释了错误原因,指出指定编码必须使用encoding='utf-8',否则解释器会将其视为buffering参数并要求整数

今天调试代码遇到的问题

TypeError: an integer is required (got type str)

问题原因

在python3的打开文件对象的open函数,

以下为错误写法:

 read_helper=open(checkpath,"r","utf-8")

对于第三个参数,指定编码方式必须要加encoding=“utf-8”

read_helper=open(checkpath,"r",encoding="utf-8")

如果不加encoding=,则解释器默认认为第三个参数为指定buffering,

这个变量本身要传入一个整形变量才行:

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):

而对于二进制读取的模式,则不能制定编码方法,

正确写法如下:

read_helper=open(checkpath,"rb")

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文