python write()参数错误,导致报错TypeError: a bytes-like object is required, not 'str'
2018-03-05 12:31
1726 查看
# -*- coding: utf-8 -*- import random,string filerad = open('C:/Users/Administrator/Desktop/randomnum.txt','wb') for i in range(200): chars = string.ascii_letters + string.digits list = [ random.choice(chars) for i in range(8)] snew = ''.join(list) + '\n' #print(snew) #filerad.write(snew.encode()) filerad.write('{0}\n'.format(''.join(snew))) filerad.close()
使用write函数时,出现报错
我觉得很奇怪,write函数为什么要求byte,而不是str?
根据报错查找后,通过encode()将str改为byte后,编译通过。但是这显然不是真正的原因
检查open函数,发现参数写为‘wb’,即按二进制write,所以后面出现TypeError: a bytes-like object is required, not 'str'的报错,将此次的参数修改为w后,编译通过,write的结果正确
filerad = open('C:/Users/Administrator/Desktop/randomnum.txt','wb')以下为open模式:(转自 http://blog.163.com/y845766643@126/blog/static/17104630220101123113029840/) r+: Open for reading and writing. The stream is positioned at the beginning of the file. w+:Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file. r+具有读写属性,从文件头开始写,保留原文件中没有被覆盖的内容; w+具有读写属性,写的时候如果文件存在,会被清空,从头开始写。 r 打开只读文件,该文件必须存在。
r+ 打开可读写的文件,该文件必须存在。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。
a+ 以附加方式打开可读写的文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾后,即文件原先的内容会被保留。
上述的形态字符串都可以再加一个b字符,如rb、w+b或ab+等组合,加入b 字符用来告诉函数库打开的文件为二进制文件,而非纯文字文件。不过在POSIX系统,包含Linux都会忽略该字符。
相关文章推荐
- python3中,socket使用send函数时出现的错误:TypeError: a bytes-like object is required, not 'str'
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- python socket send 函数 报错:TypeError: a bytes-like object is required, not 'str'
- python3.5 模拟UDP客户端发送数据报文,报错:TypeError: a bytes-like object is required, not 'str'
- Python中3+版本运行2+版本程序出现TypeError: a bytes-like object is required, not 'str'之读取PDF中的图片
- Python 3.x: TypeError: a bytes-like object is required, not 'str'
- python中Base64编码和解码:TypeError: a bytes-like object is required, not 'str'
- python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file
- Python 3.x Error:TypeError: a bytes-like object is required, not 'str'
- TypeError: a bytes-like object is required, not 'str'
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- TypeError: a bytes-like object is required, not 'str'
- Python学习中出现TpyeErrora bytes-like object is required, not 'str'
- 解决python3的pickle.load错误:a bytes-like object is required, not 'str'
- linux下运行python3出现TypeError: a bytes-like object is required, not 'str'
- 【Python】TypeError: a bytes-like object is required, not 'str'解决
- python3 TypeError: a bytes-like object is required, not 'str'
- 【Python】TypeError: a bytes-like object is required, not 'str'解决
- Python 读写文件 中文乱码 错误TypeError: write() argument must be str, not bytes+
- python问题:TypeError: a bytes-like object is required, not 'str'