|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- f = open('record.txt','rt') #以只读方式打开record.txt文档
- boy = [] #存放小甲鱼的内容
- girl = [] #存放小客服的内容
- count = 1 #计数一共多少段内容
- for each_line in f: #读取文档内每一行字符串
- if each_line[:5] != '=====': #当提取字符串内容的前5个字符不等于'=====',分割字符串并保存到对应列表内
- (role,line_spoken) = each_line.split(':',1)
- if role == '小甲鱼':
- boy.append(line_spoken)
- else:
- girl.append(line_spoken)
- else: #相等则将当前列表内的内容保存到相应文件内
- file_boy_name = '%s%c%d.txt' %('boy','_',count)
- file_girl_name = '%s%c%d.txt' %('girl','_',count)
- f1 = open(file_boy_name,'xt')
- f1.writelines(boy)
- f2 = open(file_girl_name,'xt')
- f2.writelines(girl)
- boy = []
- girl = []
- f1.close()
- f2.close()
- count += 1
- file_boy_name = '%s%c%d.txt' %('boy','_',count) #将第三段内容保存到各自文档内
- file_girl_name = '%s%c%d.txt' %('girl','_',count)
- f1 = open(file_boy_name,'xt')
- f1.writelines(boy)
- f2 = open(file_girl_name,'xt')
- f2.writelines(girl)
- boy = []
- girl = []
- f1.close()
- f2.close()
- f.close() #关闭刚开始打开的record.txt文件
复制代码
问题:
f1 = open(file_boy_name,'xt')
f1.writelines(boy)
'xt'也表示能够写入吗?
t表示文本文件,可省略
w,x,a在文件不存在时效果一样
如果文件已存在:
x则报错:FileExistsError: [Errno 17] File exists: '文件名'
w则覆盖原文件
a则在源文件后面写。
|
|