python之文件切割保存

Posted 知_行

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python之文件切割保存相关的知识,希望对你有一定的参考价值。

最近在看小甲鱼的视频,把写的文件切割代码拿出来捋捋

#-*- 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!

以上是关于python之文件切割保存的主要内容,如果未能解决你的问题,请参考以下文章

OpenCV+Python实现将车牌数字分割为单个的字符图片

Shell脚本切割日志

python颜色压缩的结果颜色比保存颜色深

片段被视图分页器布局切割

python之字符串切割

python之模块和包