Python3.x下write()方法的一些坑

        今天,我用write()方法做了一些事情,结果有错误代码:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
--可爱的马赛克-- in <module>()
      4 f = open("./data/data.txt", "wb")
      5
----> 6 f.write("\n")
      7
TypeError: a bytes-like object is required, not 'str'

        代码:
#!python3
# -*- coding: UTF-8 -*-
f = open("./data/data.txt", "wb")
f.write("\n")

        通过我上网Google,我发现是write()方法默认接受一个“byte”类型的字符串参数,而Python3.x下字符串默认为“UTF-8”惹的祸,所以,更改成:
#!python3
# -*- coding: UTF-8 -*-
f = open("./data/data.txt", "wb")
f.write(b"\n")

        完美。

1人评论了“Python3.x下write()方法的一些坑”

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

返回顶部