標籤:讀取 open decode gbk strong style padding 修改 import
本節重點
掌握檔案的讀、寫、修改方法
掌握檔案的處理模式的區別
一.檔案讀取
? ?1.讀取全部內容
# 一次性讀取檔案f = open("test.txt",‘r‘,encoding=‘gbk‘)data = f.read()print(data)
f.close()
?2.按行讀取
# 按行讀取f = open("test.txt",‘r‘,encoding=‘gbk‘)data = f.readline()print(data,end=‘‘)
f.close()
? ?3.迴圈讀取
# 迴圈讀取f = open("test.txt",‘r‘,encoding=‘gbk‘)for line in f: print(line,end=‘‘)
f.close()
?4.二進位讀取
# 二進位讀取f = open("test.txt",‘rb‘)data = f.read()print(data.decode(‘gbk‘))
f.close()
?5.按字元讀取
# 按位元組讀取f = open("test.txt",‘r‘,encoding=‘gbk‘)data = f.read(1)print(data)
f.close()f = open("test.txt",‘r‘,encoding=‘gbk‘)data = f.readline(2)print(data)
f.close() 二.檔案寫入
?1.清空原內容寫入
# 清空原內容寫入f = open(‘test.txt‘,‘w‘,encoding=‘gbk‘)f.wirte(‘新內容,新世界‘)f.close() # 關閉並儲存
? ?2.追加內容
# 清空原內容寫入f = open(‘test.txt‘,‘a‘,encoding=‘gbk‘)f.wirte(‘新內容,新世界‘)f.close() # 關閉並儲存
?3.二進位寫入
# 清空原內容寫入f = open(‘test.txt‘,‘wb‘)f.wirte(‘新內容,新世界‘.encode(‘gbk‘))f.close() # 關閉並儲存
?4.flush儲存
# flush強刷儲存內容f = open(‘test2.txt‘,‘w‘,encoding=‘gbk‘)f.write(‘新內容,新世界3‘)f.flush() #儲存內容#f.close()
三.檔案修改
? ?1.一次性修改,佔用cpu
# 一次性修改f = open("test.txt",‘r+‘,encoding=‘gbk‘)data = f.read()f.seek(0)f.truncate()data = data.replace(‘Zi‘,‘子‘)f.write(data)f.close()
?2.邊讀邊改,佔用硬碟
# 邊讀邊改import osf_name = "test.txt"f_temp_name = "test_temp.txt"f = open(f_name,‘r‘,encoding=‘gbk‘)f_temp = open(f_temp_name,‘w‘,encoding=‘gbk‘)for line in f: f_temp.write(line.replace(‘子‘,‘Zi‘))f.close()f_temp.close()os.replace(f_temp_name,f_name)
python學習之路 四 :檔案處理