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设计】。

相关文章

Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例

Python2.7基于笛卡尔积算法实现N个数组的排列组合运算示例

本文实例讲述了Python2.7基于笛卡尔积算法实现N个数组的排列组合运算。分享给大家供大家参考,具体如下: 说明:本人前段时间遇到的求n个数组的所有排列组合的问题,发现笛卡尔积算法可以...

Python面向对象特殊成员

类的特殊成员之call #!/usr/bin/env python # _*_coding:utf-8 _*_ class SpecialMembers: # 类的构造方法...

Python实现统计单词出现的个数

最近在看python脚本语言,脚本语言是一种解释性的语言,不需要编译,可以直接用,由解释器来负责解释。python语言很强大,而且写起来很简洁。下面的一个例子就是用python统计单词出...

python 识别图片中的文字信息方法

python 识别图片中的文字信息方法

最近朋友需要一个可以识别图片中的文字的程序,以前做过java验证码识别的程序; 刚好最近在做一个python项目,所以顺便用Python练练手 1.需要的环境: 2.7或者3.4版本的p...

Python3最长回文子串算法示例

本文实例讲述了Python3最长回文子串算法。分享给大家供大家参考,具体如下: 1. 暴力法 思路:对每一个子串判断是否回文 class Solution: def longes...