open(file_name,mode,encoding)輸出參數:
file_name = 'a.txt' # 以相對路徑打開(優先使用,可移植性強) ''' a.txt # 與當前py程序在同一級目錄下 r'dir\a.txt' # 在當前路徑的子目錄dir下的a.txt ''' file_name = r'D:\PYTHON\OLDBOY\DAY7\a.txt' # 以絕對路徑打開 #********************************************************** mode = 'rt' 'rb' # 只讀模式打開,r表示文本模式,b表示字節模式。對於圖片、音頻、視頻等文件需要用字節模式操作 ''' 1.文件不存在會報錯 2.文件指針移到文件開頭 ''' mode = 'wt' 'wb' # 只寫模式打開 ''' 1.文件不存在則創建文件,指針在文件開頭 2.文件存在則會清空文件內容,指針在文件開頭 ''' mode = 'at' 'ab' # 追加模式打開(只寫),指針在文件末尾 ''' 1.文件不存在則創建文件,指針在文件開頭 2.文件存在則將指針移到文件尾。(所寫入的內容追加到文件尾) ''' #********************************************************** encoding = 'utf-8' encoding = 'GBK' ''' 指定文件的打開編碼模式(文件以什么編碼存,就以什么編碼打開) 即可保證不亂碼 當以字節模式打開時,該參數不可設置! ''' #********************************************************** open(file_name, mode, encoding=encoding)
open()方法返回一個文件對象,使用完畢后需要調用f.close()方法釋放文件對象。python中提供了更簡潔的方式:
with open('a.txt','r') as f: pass
# 在with代碼塊下的語句都執行完時,會自動釋放文件內存。
文件對象的內置方法:
with open('a.txt','r',encoding='utf-8') as f: data = f.read() # 一次性讀取所有內容到內存中 print(data) with open('a.txt','r',encoding='utf-8') as f: data = f.readline() # 讀取一行內容到內存中 print(data) with open('a.txt','r',encoding='utf-8') as f: data = f.readlines() # 一次性讀取所有內容,以每行內容作為元素返回一個列表 print(data)
with open('a.txt','w',encoding='utf-8') as f: f.write('哈哈哈哈') f.writelines(['哈哈哈','啊啊啊啊'])
**********************************************************************************************
關於讀寫要注意的地方:
當以w方式打開一個文件,調用f.write()的方法時,寫入的數據在內存中,注意:在f.close()之后才會寫入到硬盤之中。
當以r方式打開一個文件,調用f.read()的方法時,將實時讀取硬盤中的數據。(內部機制可能時句柄,操作系統會向句柄管理員實時匯報內容)
驗證代碼:
監控:
import time with open('c.txt','r',encoding='utf-8')as f: f.seek(0,2) while True: res = f.readline() if res: print(res,end='') else: time.sleep(0.5)
寫入:
import time with open('c.txt', 'a', encoding='utf-8') as f: while True: time.sleep(1) print('zhengzaishuru') f.write(time.strftime('%Y-%m-%d %H:%M:%S\n'))
將監控不到任何數據,原因就是:在寫入未運行close()之前,內容不會被寫入。而中斷程序,將不會運行close()方法。所以c.txt里的內容不會有任何變化。
加入flush()將寫入的內容存儲至硬盤
import time with open('c.txt', 'a', encoding='utf-8') as f: while True: time.sleep(1) print('zhengzaishuru') f.write(time.strftime('%Y-%m-%d %H:%M:%S\n')) f.flush()