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可以直接将字符串写入到目标文件中


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM