Python2随机写入二进制文件: with open('/python2/random.bin','w') as f: f.write(os.urandom(10)) 但使用Python3会报错: TypeError:must be str, not bytes 原因为:Python3给open函数添加了名为encoding的新参数,而这个新参数的默认值却是'utf-8'.这样在文件句柄上进行read和write操作时,系统就要求开发者必须传入包含Unicode字符的实例,而不接受包含二进制数
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 un
写入文件代码如下: with open("e:\\test01.txt","w+",encoding="utf-8") as wq: for i in range(1,10): for j in range(1,i+1): wq.write(str(j)+"*"+str(i)+"="+str(i*j)+" ") wq.write("\n")