python分割一个文本为多个文本的方法分割一个文本为多个文本的方法
主要为大家详细介绍了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('')
output_content = '' # clear content of output file
else:
output_content += line # append content
write_file(outfilename,output_content) #for the last file
评论0