028一个任务课堂
f = open('D:\\record.txt')boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != "======":
(name,words) = each_line.split(":",1)
if name == '小甲鱼':
boy.append(words)
else:
girl.append(words)
else:
boy_file_name = "boy" + str(count) + '.txt'
girl_file_name = "girl" + str(count) + ".txt"
boy_file = open(boy_file_name,"w")
girl_file = open(girl_file_name,"w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
boy_file_name = "boy" + str(count) + '.txt'
girl_file_name = "girl" + str(count) + ".txt"
boy_file = open(boy_file_name,"w")
girl_file = open(girl_file_name,"w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
为什么在第五行for 语句报错了??
UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 4: illegal multibyte sequence
这一句
f = open('D:\\record.txt')
改成下面这样试试
f = open('D:\\record.txt' , encoding = 'utf8') 编码问题。楼主文件存储的编码为 UTF-8,但 Python 默认以 GBK 的编码打开文件,所以需要修改打开文件使用的编码:
f = open('D:\\record.txt', encoding='utf-8')
boy = []
girl = []
count = 1
for each_line in f:
if each_line[:6] != "======":
(name,words) = each_line.split(":",1)
if name == '小甲鱼':
boy.append(words)
else:
girl.append(words)
else:
boy_file_name = "boy" + str(count) + '.txt'
girl_file_name = "girl" + str(count) + ".txt"
boy_file = open(boy_file_name,"w")
girl_file = open(girl_file_name,"w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1
boy_file_name = "boy" + str(count) + '.txt'
girl_file_name = "girl" + str(count) + ".txt"
boy_file = open(boy_file_name,"w")
girl_file = open(girl_file_name,"w")
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
boy = []
girl = []
count += 1 jackz007 发表于 2019-11-20 17:58
这一句
改成下面这样试试
f = open('D:\\record.txt' , encoding = 'utf8')
,为中文符号 zltzlt 发表于 2019-11-20 19:31
编码问题。楼主文件存储的编码为 UTF-8,但 Python 默认以 GBK 的编码打开文件,所以需要修改打开文件使用 ...
神奇。。。{:5_106:}
jackz007 发表于 2019-11-20 17:58
这一句
改成下面这样试试
{:5_106:}
页:
[1]