1. 程式人生 > 其它 >8.1檔案:因為懂你,所以永恆

8.1檔案:因為懂你,所以永恆

檔案的開啟模式

檔案物件方式

任務:將檔案中的資料進行分割並按照以下規律儲存起來:

–小甲魚的對話單獨儲存為boy_*.txt的檔案(去掉“小甲魚:”)

–小客服的對話單獨儲存為girl_*.txt的檔案(去掉“小客服:”)

–檔案中總共有三段對話,分別儲存為boy_1.txt, girl_1.txt,boy_2.txt, girl_2.txt共4個檔案

原始檔案:

小客服:小甲魚,有個好評很好笑哈。
小甲魚:哦?
小客服:“有了小甲魚,以後媽媽再也不用擔心我的學習了~”
小甲魚:哈哈哈,我看到吖!

結果:

 1 d = open('talk.txt',encoding = 'UTF-8'
) 2 d.seek(0,0) 3 i = 0 4 j = 0 5 for each in d: 6 if each[:4] == '小客服:': 7 i += 1 8 new_file_girl = 'gril_' + str(i) + '.txt' 9 new = open(new_file_girl,'w') 10 new.write(each[4:]) 11 new.close() 12 else: 13 j += 1 14 new_file_boy = '
boy_' + str(j) + '.txt' 15 new = open(new_file_boy,'w') 16 new.write(each[4:]) 17 new.close() 18 d.close()