之前我們從檔案中進行讀取資料,並把讀取到的資料進行了簡單的處理,然後通過print語句進行了列印。但是很多時候我們是需要把處理後的資料儲存到檔案中的,所以這裡我們接著介紹如何把處理後的資料儲存到檔案,因為在之前只是對資料進行了非常簡單的處理,這裡首先對資料做一些複雜的處理。
程式處理資料編寫一段代碼實現以下功能:建立兩個名為man和other的空列表,讀取sketch.txt檔案中的內容(此檔案在【Python實戰04】中有),並使用“:”進行分割,分別儲存為role和line_spoken,然後通過role為man或者other,將對應說的內容分別儲存到對應的man和other列表中。
代碼如下:
man= []other = []try: data = open('sketch.txt') for each_line in data: try: (role,line_spoken) = each_line.split(":",1) line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) except ValueError: pass data.close()except IOError: print('The datafile is missing!')print(man)print(other)
運行結果如下:
>>> ================================ RESTART ================================>>> ['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]>>>
接著我們要做的工作就是把列表man和other中的內容儲存到檔案,首先就是要以寫的方式開啟一個檔案。
以寫入模式開啟一個檔案代碼如下:
out = open('sketch.txt','w')
這裡我們以寫的模式開啟了sketch.txt,然後我們可以通過以下語句將內容寫到這個檔案,如下:
print('Hello World',file=out)
這樣我們就把Hello World這個字串寫入到了sketch.txt檔案中去了,最後別忘了關閉流:
out.close()
然後我們就可以改寫之前的代碼,將man和other列表的內容分別儲存至man_data.txt和other_data.txt中,代碼如下:
man= []other = []try: data = open('sketch.txt') for each_line in data: try: (role,line_spoken) = each_line.split(":",1) line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) except ValueError: pass data.close()except IOError: print('The datafile is missing!')print(man)print(other)try: man_file = open('man_data.txt','w') other_file = open('other_data.txt','w') print(man,file=man_file) print(other,file=other_file) man_file.close() other_file.close()except IOError: print('File Error')
可以看到我們只是在之前的代碼最後加入了檔案的寫操作,其他的代碼並沒有改動。執行以上的代碼,可以發現在對應的檔案夾中產生了一下的兩個檔案:
兩個檔案的內容分別如下:man_data.txt:
['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
other_data.txt:
["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]
但是此時我們的代碼相對脆弱,因為在最後進行檔案關閉時,如果第一個man_file.close()執行錯誤的話,則第二個other_file.close()則不會被執行,此時就導致了other_file的關閉失敗,此時我們可以通過finally語句進行限制。用finally拓展try這裡我們可以把資料關閉操作直接放置到finally語句中進行操作,如下:
man= []other = []try: data = open('sketch.txt') for each_line in data: try: (role,line_spoken) = each_line.split(":",1) line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) except ValueError: pass data.close()except IOError: print('The datafile is missing!')print(man)print(other)try: man_file = open('man_data.txt','w') other_file = open('other_data.txt','w') print(man,file=man_file) print(other,file=other_file)except IOError: print('File Error')finally: man_file.close() other_file.close()
運行結果是和之前一樣的,同樣會產生對應的兩個檔案,不同的是處理錯誤的能力增強了。
補充:這裡我們也可以對錯誤類型的詳細資料進行列印,比如開啟檔案進行讀取時,我們可以列印當前錯誤的詳細資料,代碼如下:
try: data = open('sketch1.txt')except IOError as err: print('File Error:'+str(err))
這裡為IOError異常起了一個別名err,並列印err中的內容,因為err為一個對象,所以使用str函數來列印對象的具體內容。結果如下:
>>> ================================ RESTART ================================>>> File Error:[Errno 2] No such file or directory: 'sketch1.txt'>>>
這裡就直接提示說當前沒有找到sketch1.txt檔案。