美文网首页
python3.X与2.X文件读写中的更改

python3.X与2.X文件读写中的更改

作者: KatherineJI | 来源:发表于2017-06-28 18:13 被阅读0次

先介绍一下 python bytes和str两种类型转换的函数encode(),decode()

str通过encode()方法可以编码为指定的bytes

bytes通过decode()方法可以将bytes编码为str

举个栗子

fo =open("foo.txt","wb")

str ="www.room.com!Very good site!"

fo.write(str)

fo.close()

运行之后报错:

Traceback (most recent call last):  File "E:/Python练习/Tony.py", line 6, info.write(str)

TypeError: a bytes-like object is required, not 'str'  (需要的是bytes数据类型,不是str)

修改:

fo=open("foo.txt","wb")

str ="www.room.com!Very good site!"

fo.write(str.encode())

fo.close()

运行正确

相关文章

网友评论

      本文标题:python3.X与2.X文件读写中的更改

      本文链接:https://www.haomeiwen.com/subject/nlzucxtx.html