python分割一个文本为多个文本的方法
2020-03-11 16:12
639 查看
本文实例为大家分享了python分割一个文本为多个文本,供大家参考,具体内容如下
# load file # for each row ## if match ## output def main(): file_source = './reading_questions.txt' #target_dir = '' file_in = open(file_source,'r') template_str = 'TARGET' outfilename = './head.txt' output_content = '' while 1: line = file_in.readline() if not line: break if line.find(template_str) != -1: write_file(outfilename,output_content) outfilename = './'+line+'.txt' # output file tile output_content = '' else: output_content += line # append write_file(outfilename,output_content) #for the last file # close file stream file_in.close() def write_file(filename, filecontent): file_out = open(filename,'w') # create file file_out.write(filename) file_out.write(filecontent) file_out.close() main()
cygwin+python3下报错:UnicodeDecodeError: 'gb2312' codec can't decode byte 0xac in position 25: illegal multibyte sequence
修改打开文件参数
file_in = open(file_source,'r',encoding='UTF-8')
修改为如下
# load file # for each row ## if match ## output def main(): print ('hhh') file_source = 'listening_questions.txt' #target_dir = ''file_in = open(file_source,'r',encoding='UTF-8') template_str = 'ZTPO' outfilename = 'head' #first file before match target output_content = '' while 1: line = file_in.readline() if not line: break if line.find(template_str) != -1: write_file(outfilename,output_content) outfilename = line.strip('\n') output_content = '' # clear content of output file else: output_content += line # append content write_file(outfilename,output_content) #for the last file # close file stream file_in.close() def write_file(filename, filecontent): outfilename = './'+filename+'.txt' # output file tile file_out = open(outfilename,'w',encoding='UTF-8') # create file file_out.write(filename) file_out.write(filecontent) file_out.close() main()
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- 合并多个python list以及合并多个 django QuerySet 的方法在用python或者django写一些小工具应用的时候,有可能会遇到合并多个list到一个 list 的情况。单纯从技
- ffmpeg 将文本转换成音频以及多个音频合成一个音频的方法
- Python将一个大文件按段落分隔为多个小文件的简单方法
- python实现对一个完整url进行分割的方法
- Python将一个大文件按段落分隔为多个小文件的简单方法
- Python实现对一个函数应用多个装饰器的方法示例
- python统计一个文本中重复行数的方法
- python统计一个文本中重复行数的方法
- python 删除字符串中连续多个空格并保留一个的方法
- C#中同一个类的多个构造方法之间的调用
- 编程有时候我们需要给方法返回一个值 但由于需要返来多个 所有 可以定义一个类
- 存储过程分割一个字段为多个值
- 一个比String.split分割速度更快的分割方法
- 如何用正则将多个空格看成一个空格结合spllit()方法将文本数据入库
- ASP.NET防止同一个帐号多个用户同时登陆的解决方法
- python判断某个对象是否可以做一个字典的键多方法
- 一个Action中有多个方法的校验(validation)方式
- 一个IIS下多个站点的方法
- 一个jetty部署多个项目配置之方法一
- *.zip.001 & *.zip.002类型的文件的解压缩方法 即如何合并多个被分割的文件