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

相关文章

Python3 导入上级目录中的模块实例

python导入同级别模块很方便: import xxx 要导入下级目录页挺方便,需要在下级目录中写一个__init__.py文件 from dirname import xx...

python3 shelve模块的详解

python3 shelve模块的详解 一、简介   在python3中我们使用json或者pickle持久化数据,能dump多次,但只能load一次,因为先前的数据已经被后面dump的...

django框架F&Q 聚合与分组操作示例

本文实例讲述了django框架F&Q 聚合与分组操作。分享给大家供大家参考,具体如下: F 使用查询条件的值,专门取对象中某列值的操作,可以对同一个表中的两个列进行比较 from d...

详解Django 中是否使用时区的区别

起步 在 Django 的模型中新加了一个日期的字段: import datetime class Instance(models.Model): ... start_ti...

微信跳一跳python辅助软件思路及图像识别源码解析

微信跳一跳python辅助软件思路及图像识别源码解析

本文将梳理github上最火的wechat_jump_game的实现思路,并解析其图像处理部分源码 首先废话少说先看效果 核心思想 获取棋子到下一个方块的中心点的距离 计算触摸屏...