关于031讲动动手0
为什么我在分割语句那里总是错误,提示 TypeError: a bytes-like object is required, not 'str'import pickle
def split_file(file_name):
boy = []
girl = []
count = 1
f = open('record.txt', 'rb')
for each_line in f:
if each_line[:6] != '======':
(name, words) = each_line.split(':', 1) #就是这个':'
if name == '小甲鱼':
boy.append(words)
if name == '小客服':
girl.append(words)
else:
boy_file_name = 'boy_' + str(count) + '.txt'
girl_file_name = 'girl_' + str(count) + '.txt'
boy_file = open(boy_file_name, 'wb')
girl_file = open(girl_file_name, 'wb')
pickle.dump(boy, boy_file)
pickle.dump(girl, girl_file)
boy_file.close()
girl_file.close()
count += 1
boy = []
girl = []
boy_file_name = 'boy_' + str(count) + '.txt'
girl_file_name = 'girl_' + str(count) + '.txt'
boy_file = open(boy_file_name, 'wb')
girl_file = open(girl_file_name, 'wb')
pickle.dump(boy, boy_file)
pickle.dump(girl, girl_file)
boy_file.close()
girl_file.close()
split_file('record.txt')
用小甲鱼的答案这里就可以,用我的就不行{:5_100:} 本帖最后由 java2python 于 2020-6-19 21:02 编辑
百度检索很重要:
https://www.cnblogs.com/qiuya/p/10853383.html
Python报“TypeError:abytes-likeobjectisrequired,not‘str’”解决办法
解决办法非常的简单,只需要用上python的bytes和str两种类型转换的函数encode()、decode()即可!
str通过encode()方法可以编码为指定的bytes;
反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法;
例:
str = 'this is test'
str = str.encode()
本帖最后由 永恒的蓝色梦想 于 2020-6-19 21:02 编辑
文本文件用 rb,天秀
其他的还没看import pickle
def split_file(file_name):
boy = []
girl = []
count = 1
f = open('record.txt')
for each_line in f:
if each_line[:6] != '======':
(name, words) = each_line.split(':', 1) #就是这个':'
if name == '小甲鱼':
boy.append(words)
if name == '小客服':
girl.append(words)
else:
boy_file_name = 'boy_' + str(count) + '.txt'
girl_file_name = 'girl_' + str(count) + '.txt'
boy_file = open(boy_file_name, 'wb')
girl_file = open(girl_file_name, 'wb')
pickle.dump(boy, boy_file)
pickle.dump(girl, girl_file)
boy_file.close()
girl_file.close()
count += 1
boy = []
girl = []
boy_file_name = 'boy_' + str(count) + '.txt'
girl_file_name = 'girl_' + str(count) + '.txt'
boy_file = open(boy_file_name, 'wb')
girl_file = open(girl_file_name, 'wb')
pickle.dump(boy, boy_file)
pickle.dump(girl, girl_file)
boy_file.close()
girl_file.close()
split_file('record.txt')
java2python 发表于 2020-6-19 21:01
百度检索很重要:
https://www.cnblogs.com/qiuya/p/10853383.html
Python报“TypeError:abytes-likeobje ...
那么我想知道 小甲鱼给的答案是直接用':'进行分割,上次我在做029讲习题的时候也是这样直接从文件中读取,也是直接用‘:’进行分割,都没有使用encode()的方法,为什么这次我使用的时候就提示报错了? 丿autistic 发表于 2020-6-19 21:16
那么我想知道 小甲鱼给的答案是直接用':'进行分割,上次我在做029讲习题的时候也是这样直接从文件中读 ...
第9行: f = open('record.txt', 'rb')你打开方式是 rb,读出来的是 bytes。 永恒的蓝色梦想 发表于 2020-6-19 21:18
第9行:你打开方式是 rb,读出来的是 bytes。
{:5_100:}没注意到这里,谢谢解答
页:
[1]