python分割一个文本为多个文本的方法
本文实例为大家分享了python分割一个文本为多个文本,供大家参考,具体内容如下
#loadfile #foreachrow ##ifmatch ##output defmain(): file_source='./reading_questions.txt' #target_dir='' file_in=open(file_source,'r') template_str='TARGET' outfilename='./head.txt' output_content='' while1: line=file_in.readline() ifnotline: break ifline.find(template_str)!=-1: write_file(outfilename,output_content) outfilename='./'+line+'.txt'#outputfiletile output_content='' else: output_content+=line#append write_file(outfilename,output_content)#forthelastfile #closefilestream file_in.close() defwrite_file(filename,filecontent): file_out=open(filename,'w')#createfile file_out.write(filename) file_out.write(filecontent) file_out.close() main()
cygwin+python3下报错:UnicodeDecodeError:'gb2312'codeccan'tdecodebyte0xacinposition25:illegalmultibytesequence
修改打开文件参数
file_in=open(file_source,'r',encoding='UTF-8')
修改为如下
#loadfile #foreachrow ##ifmatch ##output defmain(): print('hhh') file_source='listening_questions.txt' #target_dir='' file_in=open(file_source,'r',encoding='UTF-8') template_str='ZTPO' outfilename='head'#firstfilebeforematchtarget output_content='' while1: line=file_in.readline() ifnotline: break ifline.find(template_str)!=-1: write_file(outfilename,output_content) outfilename=line.strip('\n') output_content=''#clearcontentofoutputfile else: output_content+=line#appendcontent write_file(outfilename,output_content)#forthelastfile #closefilestream file_in.close() defwrite_file(filename,filecontent): outfilename='./'+filename+'.txt'#outputfiletile file_out=open(outfilename,'w',encoding='UTF-8')#createfile file_out.write(filename) file_out.write(filecontent) file_out.close() main()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。