Advertisement

python 报错:TypeError: a bytes-like object is required, not 'str'

阅读量:

TypeError: a bytes-like object is required, not ‘str’

今天在处理Python脚本的时候遇到了这样一个错误

TypeError: a bytes-like object is required, not ‘str’

我在处理用python处理一个文件读写的时遇到的,代码如下:

复制代码
    f = open("./hosts.txt",'r')
    hosts = [ip.strip('\n') for ip in f]
    f_write = open("./good_ip.txt", "wb")
    for ip in hosts:
    	f_write.write(ip)

python3 对字符串和字节码进行了明确的规定:str与bytes。数据在存储时采用字节码形式,在Python3中不会自动将str转为bytes,默认情况下需将需要保存的字符串进行转换处理:通过decode与encode指令来实现

decode() bytes–>str
encode() str -->bytes

所以上面的代码改为下面这样即可:

复制代码
    f = open("./hosts.txt", 'r')
    hosts = [ip.strip('\n') for ip in f]
    f_write = open("./good_ip.txt", "wb")
    for ip in hosts:
    	ip = ip.encode()
    	f_write.write(ip)

全部评论 (0)

还没有任何评论哟~