在执行一个将文件(record.txt)中的数据进行分割并按规定保存起来的程序时,报错,在此进行记录,方便后期复习记忆。
f = open('E:\\python\\fishc-learing\\record.txt')
a = []
b = []
count = 1
for each_line in f:
if each_line[:3] != '===':
#字符串分割操作
(role, line_spoken) = each_line.split(':', 1)
if role == 'a':
a.append(line_spoken)
if role == 'b':
b.append(line_spoken)
else:
#文件的分别保存操作
file_name_a = 'a_' + str(count) + '.txt'
file_name_b = 'b_' + str(count) + '.txt'
a_file = open(file_name_a, 'w')
b_file = open(file_name_b, 'w')
a_file.writelines(a)
b_file.writelines(b)
a_file.close()
b_file.close()
a = []
b = []
count += 1
#文件的分别保存操作
file_name_a = 'a_' + str(count) + '.txt'
file_name_b = 'b_' + str(count) + '.txt'
a_file = open(file_name_a, 'w')
b_file = open(file_name_b, 'w')
a_file.writelines(a)
b_file.writelines(b)
a_file.close()
b_file.close()
f.close()
def save_file(a,b,count):
#文件的分别保存操作
file_name_a = 'a_' + str(count) + '.txt'
file_name_b = 'b_' + str(count) + '.txt'
a_file = open(file_name_a, 'w')
b_file = open(file_name_b, 'w')
a_file.writelines(a)
b_file.writelines(b)
a_file.close()
b_file.close()
def split_file(file_name):
f = open('E:\\python\\fishc-learing\\record.txt')
a = []
b = []
count = 1
for each_line in f:
if each_line[:3] != '===':
#字符串分割操作
(role, line_spoken) = each_line.split(':', 1)
if role == 'a':
a.append(line_spoken)
if role == 'b':
b.append(line_spoken)
else:
save_file(a,b,count)
a = []
b = []
count += 1
save_file(a,b,count)
f.close()
split_file('record.txt')