Python分割文件并分别保存

来源:互联网 发布:淘宝卖电子产品 编辑:程序博客网 时间:2024/06/06 12:41

1、新建一个名为"1.text"的文件,并写入一下内容。

小明:哈哈哈哈
小红:呵呵呵呵
小明:嘿嘿嘿嘿
小红:嘻嘻嘻嘻
==================================================
小明:飒飒飒飒
小红:走走走走
小明:坎坎坷坷
小红:啦啦啦啦
==================================================
小明:哈哈哈哈2
小红:呵呵呵呵2
小明:嘿嘿嘿嘿2
小红:嘻嘻嘻嘻2
==================================================
小明:飒飒飒飒2
小红:走走走走2
小明:坎坎坷坷2
小红:啦啦啦啦2

2、要实现根据“=======================”将文件分割为对话,分别保存。新建‘file.py"文件,写入代码。

def saveFile(xm,xh,count):    file_name_xm='xm_'+str(count)+'.txt'    file_name_xh='xh_'+str(count)+'.txt'            xm_file=open(file_name_xm,'w')    xh_file=open(file_name_xh,'w')    xm_file.writelines(xm)    xh_file.writelines(xh)    f=open('D:\\aaapy\\1.txt')xm = []xh  = []count=1for each_line in f:    if each_line[:8]!='========':        (role,line_spoken)=each_line.split(':')        if role=='小明':            xm.append(line_spoken)        if role =='小红':            xh.append(line_spoken)                    else:        saveFile(xm,xh,count)        xm=[]        xh=[]        count+=1saveFile(xm,xh,count)        f.close()        

3、执行完成得到8个文件。


0 0
原创粉丝点击