文件的一个任务
小甲鱼上课的代码和我的一样,为什么我会报错?{:5_104:} (python3.7版本)自己编写代码时出现两种问题:
1.
Traceback (most recent call last):
File "D:/Python-3.7.0/python-3.7.0/练习/新建文件夹/text.py", line 7, in <module>
for each_line in f:
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 4: illegal multibyte sequence
2.
Traceback (most recent call last):
File "D:/Python-3.7.0/python-3.7.0/练习/新建文件夹/text.py", line 9, in <module>
(name,line_spoken) = each_line.split(':', 1)
TypeError: a bytes-like object is required, not 'str'
自己写的代码:
boy = []
girl = []
count= 1
f = open(r'D:\Python-3.7.0\python-3.7.0\练习\新建文件夹\text1.txt','rb')
for each_line in f:
if each_line[:3] != '===' :
(name,line_spoken) = each_line.split(':', 1)
if name == '小甲鱼':
boy.append(line_spoken)
if name == '小客服':
girl.append(line_spoken)
else:
file_name_boy ='boy_'+str(count) + '.txt'
file_name_girl ='girl_'+str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl=[]
count+=1
f.close()
本帖最后由 xiaosi4081 于 2020-6-5 21:29 编辑
boy = []
girl = []
count= 1
f = open(r'D:\Python-3.7.0\python-3.7.0\练习\新建文件夹\text1.txt','r',encoding='utf-8')
for each_line in f:
if each_line[:3] != '===' :
(name,line_spoken) = each_line.split(':', 1)
if name == '小甲鱼':
boy.append(line_spoken)
if name == '小客服':
girl.append(line_spoken)
else:
file_name_boy ='boy_'+str(count) + '.txt'
file_name_girl ='girl_'+str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl=[]
count+=1
f.close()
1.用r模式,不是rb模式...
2.加上编码
求最佳{:10_254:} 用r模式,不是rb模式... 我看你发求助帖不结账,是一种很不好的习惯
所以建议你赶快结账 我不明白为什么要加“encoding='utf-8'”?能说说这个代码有什么用吗?{:5_106:} xiaosi4081 发表于 2020-6-6 16:11
我看你发求助帖不结账,是一种很不好的习惯
所以建议你赶快结账
求助帖还要结账? 编程大佬007 发表于 2020-6-7 11:35
求助帖还要结账?
就是设最佳 xiaosi4081 发表于 2020-6-7 12:10
就是设最佳
我已经给了最佳
页:
[1]