您的位置:首页 > 编程语言 > Python开发

python之文件切割保存

2016-06-19 11:22 405 查看
最近在看小甲鱼的视频,把写的文件切割代码拿出来捋捋

#-*- coding:utf-8 -*-
f = open('foo.txt')

man = [] #定义两个空列表
women =[]
count = 1 #初始化计数器

for each_line in f:
if each_line[:6] != '======': #如果文档未遇到分隔符,则切割
(role,line_spoken) = each_line.split(':',1)#遇到冒号则切割1次
if role == 'boy':
man.append(line_spoken) #将角色boy的话添加到man列表
if role == 'girl':
women.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(man)#将列表内容分别写入文件
girl_file.writelines(women)

boy_file.close()
girl_file.close()

man = []
women = []
count += 1

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(man)
girl_file.writelines(women)

boy_file.close()
girl_file.close()

f.close()


升级版代码捋捋

#-*- coding:utf-8 -*-

#自定义保存文件函数
def save_file(man, women, count):
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(man)
girl_file.writelines(women)

boy_file.close()
girl_file.close()

#自定义分割文件函数
def fenge(filename):
f = open(filename)

man = []
women =[]
count = 1

for each_line in f:
if each_line[:6] != '======':
(role,line_spoken) = each_line.split(':', 1)
if role == 'boy':
man.append(line_spoken)
if role == 'girl':
women.append(line_spoken)
else:
save_file(man, women, count)

man = []
women = []
count += 1

save_file(man, women, count)

f.close()

fenge('foo.txt')


END!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: