python學習之路 四 :檔案處理

來源:互聯網
上載者:User

標籤:讀取   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學習之路 四 :檔案處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.