with open('a.txt',mode='rt',encoding='utf-8')as f: res=f.read(4) print(res)
強調:只有t模式下read(n)中的n表示的是字符個數,其他都是以字節為單位。
with open('a.txt',mode='rb')as f: res=f.read(3) print(res.decode('utf-8'))
三種模式:
-
0(默認):參照文件開頭
-
1 :參照指針當前位置
-
2 :參照文件末尾
I 0模式:參照文件開頭
只有0模式既可在t下用也可在b模式下用。1.2只能在b模式下用
with open('a.txt',mode='rt',encoding='utf-8') as f: f.seek(3, 0) print(f.tell()) #顯示指針位置 print(f.read()) #參照文件開頭指針位置向后移動3個字節
II 1模式:參照指針當前位置
with open('a.txt',mode='rb')as f: f.read(3) #先讀三個字節,指針移動到3 f.seek(3, 1)#1以指針當前位置再移動3位 print(f.read().decode('utf-8'))
III 2模式:參照文件末尾
with open('a.txt',mode='rb')as f: f.seek(-5,2) #參照文件末尾,指針移動到-5 print(f.tell()) print(f.read().decode('utf-8'))
小練習:
寫一個程序監測文件中新增內容:
with open('access.log',mode='at',encoding='uft-8')as f: f.write('時間 內容 登陸名\n') #先寫一個程序:該程序就是被監測程序 import time #導入時間模塊,刷新時間 with open('access.log',mode='rb')as f: f.seek(0, 2) #將指針移到文件末尾 while True: #循環一行行讀取文件 line = f.readline() if len(line) == 0:#判斷文件長度是否為0,為0表示文件未寫入 time.sleep(1) else:#如果有文件寫入則會打印 print(line.decode('utf-8'), end='')