|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
小甲鱼上课的代码和我的一样,为什么我会报错? (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.加上编码
求最佳
|
|