Python3 写入文件

Demo:

file = open("test.txt", "wb")
file.write("string")

上面这段代码运行会报类型错误:TypeError: a bytes-like object is required, not 'str' 

wirte方法是将一个字节缓冲区写入到目标文件中,而不支持string类型

write源码:

def write(self, *args, **kwargs): # real signature unknown
"""
Write buffer b to file, return number of bytes written.

Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass

注:python3 将字符串写入到目标文件时,必须先将字符串转换为字节才能写入,python2可以直接将字符串写入到目标文件中

posted @ 2017-02-23 16:11  丶挑战者丶  阅读(4846)  评论(0)    收藏  举报