关于文件一个任务的问题
请问在文件分割保存成Boy123,girl123的任务中,出现以下错误,要如何解决呢?谢谢。ValueError: too many values to unpack (expected 2) 1,删除文件中所有的空行
2,发代码 只发一条不完整的错误信息是没用的,只能知道你某个地方的参数错误,这可能是一个逗号的问题,也可能是其他方面,所以就算不放代码也要放上完整错误信息才能解决问题 完整错误信息如下:
Traceback (most recent call last):
File "D:\PYTHON\python课后练习\28文件\test1.py", line 7, in <module>
(role,line_spoken)=each_line.split(':',1)
ValueError: not enough values to unpack (expected 2, got 1)
完整代码如下:
f=open('D:\\PYTHON\\python课后练习\\28文件\\record.txt')
boy=[]
girl=[]
count=1
for each_line in f:
if each_line[:6]!='=====':
(role,line_spoken)=each_line.split(':',1)
if role=='小甲鱼':
boy.append(line_spoken)
if role=='小客服':
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
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()
f.close() if each_line[:6]!='======':
少了个等号,所以如果这一行是============
也会进入if语句
没找到:
所以split后只有一个元素
而变量名有两个,就回报错 f=open('D:\\PYTHON\\python课后练习\\28文件\\record.txt')
boy=[]
girl=[]
count=1
for each_line in f:
if each_line[:6]!='=====':
if each[:4]=='小甲鱼':
boy.append(line_spoken)
if each[:4]=='小客服':
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
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()
f.close() 明白啦,谢谢大家!
页:
[1]