python分割一个文本为多个文本的方法

yipeiwu_com5年前Python基础

本文实例为大家分享了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设计】。

相关文章

利用python-docx模块写批量生日邀请函

利用python-docx模块写批量生日邀请函

利用python-docx模块,写批量生日邀请函 有关python-docx的使用方法,可以参考官方的API文档。这里使用了其中的一些基本功能,来完成一个简单的任务:为参加聚会的好友,每...

python OpenCV学习笔记直方图反向投影的实现

python OpenCV学习笔记直方图反向投影的实现

本文介绍了python OpenCV学习笔记直方图反向投影的实现,分享给大家,具体如下: 官方文档 – https://docs.opencv.org/3.4.0/dc/df6/tuto...

Python中print函数简单使用总结

Python中print函数简单使用总结

print函数是Python的入门,每一个学习python的人都绕不开这个函数,下面介绍一下这个函数的用法。 打开电脑,选择python软件,下面选择python 3.7为例进行介绍,点...

Django代码性能优化与Pycharm Profile使用详解

Django代码性能优化与Pycharm Profile使用详解

前言 pycharm是python的一个商业的集成开发工具,本人感觉做python开发还是很好用的,django是一个很流行的python web开源框架,本文将通过实例代码给大家介绍了...

python和pygame实现简单俄罗斯方块游戏

python和pygame实现简单俄罗斯方块游戏

本文为大家分享了python实现俄罗斯方块游戏的具体代码,供大家参考,具体内容如下 Github:Tetris 代码: # -*- coding:utf-8 -*- import...