WXF666 发表于 2019-11-20 17:21:40

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

jackz007 发表于 2019-11-20 17:58:22

      这一句
f = open('D:\\record.txt')
      改成下面这样试试
f = open('D:\\record.txt' , encoding = 'utf8')

zltzlt 发表于 2019-11-20 19:31:54

编码问题。楼主文件存储的编码为 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

zltzlt 发表于 2019-11-20 19:32:22

jackz007 发表于 2019-11-20 17:58
这一句

      改成下面这样试试

f = open('D:\\record.txt' , encoding = 'utf8')

,为中文符号

WXF666 发表于 2019-11-20 20:37:09

zltzlt 发表于 2019-11-20 19:31
编码问题。楼主文件存储的编码为 UTF-8,但 Python 默认以 GBK 的编码打开文件,所以需要修改打开文件使用 ...

神奇。。。{:5_106:}

WXF666 发表于 2019-11-20 20:37:44

jackz007 发表于 2019-11-20 17:58
这一句

      改成下面这样试试

{:5_106:}
页: [1]
查看完整版本: 028一个任务课堂