|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- count= 1
- boy = []
- girl= []
- f=open(r"C:\Users\xy\Desktop\record.txt")
- 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 = []
- girl= []
- count += 1
- file_name_boy='boy_'+ str(count) + '.txt'
- file_name_girl='girl_'+ str(count) + '.txt'
- boy_file = open((r"C:\Users\xy\Desktop\%s)" % file_name_boy),'w')
- girl_file = open((r"C:\Users\xy\Desktop\%s)" % file_name_girl),'w')
- boy_file.writelines(boy)
- girl_file.writelines(girl)
- boy_file.close()
- girl_file.close()
- f.close()
复制代码
运行后在桌面只能找到命名形式为“boy_3.txt)”和"girl_3.txt)"这两个文件,其他的也找不到。(我也不清楚为什么文件名字后有一个右括号。。)
本帖最后由 Twilight6 于 2020-6-30 09:26 编辑
for 循环里面忘记关闭文件了
- count = 1
- boy = []
- girl = []
- f = open(r"C:\Users\xy\Desktop\record.txt")
- 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 = []
- girl = []
- count += 1
- boy_file.close()
- girl_file.close()
- file_name_boy = 'boy_' + str(count) + '.txt'
- file_name_girl = 'girl_' + str(count) + '.txt'
- boy_file = open((r"C:\Users\xy\Desktop\%s" % file_name_boy), 'w')
- girl_file = open((r"C:\Users\xy\Desktop\%s" % file_name_girl), 'w')
- boy_file.writelines(boy)
- girl_file.writelines(girl)
- boy_file.close()
- girl_file.close()
- f.close()
复制代码
因为你这里字符串中有括号呀,去掉就行:
boy_file = open((r"C:\Users\xy\Desktop\%s)" % file_name_boy), 'w')
girl_file = open((r"C:\Users\xy\Desktop\%s)" % file_name_girl), 'w')
|
|