Python-文件處理-實現往文件末尾追加數據和讀取文件末尾追加的數據


#這個程序用途:往access.log文件末尾追加數據
with open(r'access.log',mode="ta",encoding="utf-8") as ta:
#a模式:打開文件指針直接跳到文件末尾
ta.write("hhhhhhhhhhh3\n")

#這個程序用途:讀取access.log文件末尾追加數據
import time
with open(r'access.log',mode="br") as tr:
#1.將指針跳到文件末尾
#tr.read() #錯誤的思路,直接將硬盤數據讀入內存,指針在文件末尾。這樣導致內存溢出
tr.seek(0,2) #指針的移動都是以bytes為單位,所以打開文件使用binary
#print(tr.tell())
while True:
res_line=tr.readline()
if len(res_line) == 0:
time.sleep(0.5)
#continue :注意這一塊不需要continue,當讀取一行的長度為0時,就重新進行while循環了
else:
print(res_line.decode("utf-8"),end="")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM