zoukankan      html  css  js  c++  java
  • 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!

  • 相关阅读:
    mybatis plus 获取新增实体的主键
    通过 Feign 进行文件上传
    mybatis plus 更新值为null的字段
    idea 配置 service 服务,多模块同时启动
    通过设置 Chrome 解决开发调用跨域问题
    xargs 命令教程
    我的Windows 10 垃圾清理秘诀(不用优化软件)
    BugReport 分析利器 ChkBugReport
    语言与地区简码大全
    linux 将内容强制输出到终端
  • 原文地址:https://www.cnblogs.com/changbo/p/5597694.html
Copyright © 2011-2022 走看看