|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 jiong_jiong 于 2020-7-14 13:47 编辑
课堂上,小甲鱼是将字符串分割后,写入boy和girl的两个列表中,再将列表写入文件。
我试着改成,不要列表,直接进行写入。最后并没有生成新文件。
想请教一下我代码哪里出了问题
- f = open(r'C:\Users\jiong\Desktop\record.txt','r')
- for each in f:
- c = 1
- filenameb='boy_'+str(c)+'.txt'
- filenameg='girl_'+str(c)+'.txt'
- if each[0:6] == '======':
- bfile.close() #找到分隔符后,对之前的文件进行关闭保存
- gfile.close()
- c = c+1
- else:
- (role,spoken)=each.split(':',1)
- if role == '小甲鱼':
- bfile = open(filenameb,'w')
- bfile.write(spoken)
- if role == '小客服':
- gfile = open(filenameg,'w')
- gfile.writelines(spoken)
-
- f.close()
复制代码
根据最佳答案改写的:
- f = open(r'C:\Users\jiong\Desktop\record.txt')
- c=1
- ##filenameb = 'boy_' + str(c) + '.txt'
- ##filenameg = 'girl_' + str(c) + '.txt'
- ##bfile = open(filenameb, 'a')
- ##gfile = open(filenameg, 'a')这几句放这里的话,filename不会变化,只会生成一个文件
- for each in f:
- filenameb = 'boy_' + str(c) + '.txt'
- filenameg = 'girl_' + str(c) + '.txt'
- bfile = open(filenameb, 'a')
- gfile = open(filenameg, 'a')
- if each[0:6] != '======':
- (role,spoken)=each.split(':',1)
- if role == '小甲鱼':
- bfile.write(spoken)
- if role == '小客服':
- gfile.write(spoken)
- else:
- bfile.close()
- gfile.close()
- c +=1
- print('c=%d'%c)
- bfile =open(filenameb,'a')
- gfile =open(filenameg,'a')
- bfile.close()
- gfile.close()
- f.close()
复制代码
重新改了下,现在可以生成三个文件了,之前只生成两个是因为 c = 2 在循环内了
- f = open(r'C:\Users\jiong\Desktop\record.txt')
- bfile = open('boy_1.txt', 'a')
- gfile = open('girl_1.txt', 'a')
- c = 2
- for each in f:
- filenameb = 'boy_' + str(c) + '.txt'
- filenameg = 'girl_' + str(c) + '.txt'
- if each[0:6] == '======':
- bfile.close() # 找到分隔符后,对之前的文件进行关闭保存
- gfile.close()
- bfile = open(filenameb, 'a')
- gfile = open(filenameg, 'a')
- c += 1
- else:
- (role, spoken) = each.split(':', 1)
- if role == '小甲鱼':
- bfile.write(spoken)
- if role == '小客服':
- gfile.write(spoken)
- bfile.close()
- gfile.close()
- f.close()
复制代码
|
|