本文實例為大家分享了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()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

