碰到bug
请教各位python鱼油:在做文件写入的作业时,我按书上的代码敲入:
def save_file(boy, girl, count):
'''establish 6 separate files'''
file_name_boy = 'boy'+ str(count)+'.txt'
file_name_girl = 'boy'+ 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()
def split_file(file_name):
count = 1
boy = []
girl = []
f = open(file_name)
for each_line in f:
if each_line != "== == ==":
(role, line_spoken) = each_line.split(':', 1)
if role == '小甲鱼':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
save_file(boy, girl, count)
boy = []
girl = []
count += 1
save_file(boy, girl, count)
f.close()
split_file('D:/record.txt')
检查几遍觉得没问题,但是在运行时,老是出现以下错误提示:
raceback (most recent call last):
File "D:\Practice\fileoperation.py", line 30, in <module>
split_file('D:/record.txt')
File "D:\Practice\fileoperation.py", line 18, in split_file
(role, line_spoken) = each_line.split(':', 1)
ValueError: not enough values to unpack (expected 2, got 1)
这是什么毛病呢?难道因为我最近下载了一些模块有关吗?
for each_line in f:
if each_line != "== == ==":
上面的等号不能有多余的空格,除非你源文件的字符就是这样
而且 each_line 应该切片,即 each_line [:6]
这个报错是因为你设置了两个变量role和line_spoken,但是变量的值却只找到一个,另一个没有被赋值,用到的方法都是Python内置的,所以并不存在安装什么模块就会造成出错的。那么报错原因就出在你的提取字符串的方法上了,这点需要看下原文件的内容,或者就像前面那位说的那个问题一样。 谢谢指正!改过来了,但是运行后是空的,无奈了.............
页:
[1]