標籤:file 進位 異常捕獲 適用於 讀寫 字串 一個 保險 under
Python中關於txt的簡單讀寫操作
常用的集中讀寫入模式:
1、r 開啟唯讀檔案,該檔案必須存在。
2、r+ 開啟可讀寫的檔案,該檔案必須存在。
3、w 開啟唯寫檔案,若檔案存在則檔案長度清為0,即該檔案內容會消失。若檔案不存在則建立該檔案。
4、w+ 開啟可讀寫檔案,若檔案存在則檔案長度清為零,即該檔案內容會消失。若檔案不存在則建立該檔案。
5、a 以附加的方式開啟唯寫檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾,即檔案原先的內容會被保留。
6、a+ 以附加方式開啟可讀寫的檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾後,即檔案原先的內容會被保留。
7、上述的形態字串都可以再加一個b字元,如rb、w+b或ab+等組合,加入b 字元用來告訴函數庫開啟的檔案為二進位檔案,而非純文字檔案。不過在POSIX系統,包含Linux都會忽略該字元。
1 讀取全部內容
try: #python3的open函數可以額外加一個encoding參數 txt_file_handle=open("1.txt","r",encoding="utf-8") #read函數:直接取讀檔案的所有內容 #參數:根據長度讀取內容 print(txt_file_handle.read(5)) print("*"*50) #readline函數:讀取檔案的遊標所在的一行 #seek(0):將檔案的遊標指向最開始的位置 txt_file_handle.seek(0) print(txt_file_handle.readline()) print(txt_file_handle.readline()) #readlines函數:去讀檔案的所有行,返回的是列表 print("*"*50) print(txt_file_handle.readlines()) print(txt_file_handle) txt_file_handle.close()except FileNotFoundError as e: print ("檔案不存在!") 2 逐行讀取
# 開啟檔案file_obj = open(txt_filename, ‘r‘)# 逐行讀取line1 = file_obj.readline()print(line1)# 繼續讀下一行line2 = file_obj.readline()print(line2)# 關閉檔案file_obj.close()
3 讀取全部內容,返回列表
# 開啟檔案file_obj = open(txt_filename, ‘r‘)lines = file_obj.readlines()for i, line in enumerate(lines): print (‘{}: {}‘.format(i, line))# 關閉檔案file_obj.close()
4 寫操作
# 開啟檔案file_obj = open(txt_filename, ‘w‘)# 寫入全部內容file_obj.write("《Python資料分析》")file_obj.close()# 開啟檔案file_obj = open(txt_filename, ‘w‘)# 寫入字串列表lines = [‘這是第%i行\n‘ %n for n in range(100)]file_obj.writelines(lines)file_obj.close()
5 推薦寫法
從上邊幾種讀寫方式中不難發現, 每次進行讀寫操作時都要調用close()函數將檔案關閉, 使用起來並不方便,所以推薦以下寫法:
try: with open("1.txt","r+",encoding="utf-8")as txt_file_handle: txt_file_handle.write()except FileNotFoundError as e: print ("檔案不存在!")
檔案操作的推薦寫法, 只要是檔案操作,保險起見都要用try except進行異常捕獲, with 寫法的特點:不需要手動close, write() 裡面填寫內容即可, 其中
with語句
- 包括了異常處理,自動調用檔案關閉操作,推薦使用
- 適用於對資源進行訪問的場合,確保無論適用過程中是否發生異常都會執行"清理"操作,如檔案關閉、線程的自動擷取與釋放等
Python中關於txt的簡單讀寫入模式與操作