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中的字符串内部换行方法

python中的字符串内部换行方法

python里有两种在字符串内部换行的方式(使用一个print打印多行字符串)。 首先使用\n的方法大家肯定都知道了。 然后是使用 ''' 三个单引号大方法。 在交互式命令行里输入pri...

Python 列表(List) 的三种遍历方法实例 详解

Python 列表(List) 的三种遍历方法实例 详解

Python 遍历 最近学习python这门语言,感觉到其对自己的工作效率有很大的提升,下面废话不多说,直接贴代码 #!/usr/bin/env python # -*- codin...

使用 Django Highcharts 实现数据可视化过程解析

使用 Django Highcharts 实现数据可视化过程解析

概述 最近在一家公司实习,入职第一个大一点的需求是将公司开发的两个winstore app的排名信息进行可视化。大概挑选了下,排除了Flask和Echarts。最终选择使用Django...

python如何求解两数的最大公约数

题目: 给定两个自然数,求这两个数的最大公约数。 分析: 单看题目的话,非常简单,我们可以循环遍历自然数,如果能够整除两个自然数,就把这个数记下来,在这些记录中找到最大的一个。 但...

Python 多个图同时在不同窗口显示的实现方法

Python的matplotlib包可以轻松的将数据可视化,博主最近遇到了一个问题,博主想同时在两个窗口展示两张图,但是代码运行结果总是显示一张图,把当前的图删掉之后才能显示另一张图。网...