python分割一個文本為多個文本的方法
本文實例為大家分享了python分割一個文本為多個文本,供大家參考,具體內(nèi)容如下
# 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
修改打開文件參數(shù)
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()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中字符串列表的相互轉(zhuǎn)換實際應(yīng)用場景
在Python編程中,經(jīng)常會遇到需要將字符串列表相互轉(zhuǎn)換的情況,這涉及到將逗號分隔的字符串轉(zhuǎn)換為列表,或者將列表中的元素連接成一個字符串,本文將深入討論這些情景,并提供豐富的示例代碼,幫助讀者更全面地理解字符串列表的轉(zhuǎn)換操作2023-12-12
Python簡單實現(xiàn)子網(wǎng)掩碼轉(zhuǎn)換的方法
這篇文章主要介紹了Python簡單實現(xiàn)子網(wǎng)掩碼轉(zhuǎn)換的方法,涉及Python字符串相關(guān)操作技巧,需要的朋友可以參考下2016-04-04
Python 通過爬蟲實現(xiàn)GitHub網(wǎng)頁的模擬登錄的示例代碼
這篇文章主要介紹了Python 通過爬蟲實現(xiàn)GitHub網(wǎng)頁的模擬登錄的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08
python 非線性規(guī)劃方式(scipy.optimize.minimize)
今天小編就為大家分享一篇python 非線性規(guī)劃方式(scipy.optimize.minimize),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

