Python 檔案I/O

來源:互聯網
上載者:User

標籤:name   print   簡單   str   utf-8   live   寫入   open   二進位   

檔案I/O是Python中最重要的技術之一,在Python中對檔案進行I/O操作是非常簡單的。

1.開啟檔案

文法:

open(name[, mode[, buffering]])

1.1檔案模式

1 ‘r‘                 讀模式2 ‘w‘                 寫入模式3 ‘a‘                 追加模式4 ‘b‘                 二進位模式(可添加到其他模式使用)5 ‘+‘                 讀/寫入模式(可添加其他模式使用)

1.2緩衝區

open 函數的第三個參數( buffering ),表示檔案的緩衝,當緩衝區大於0時(等於0時無緩衝,所有的讀寫操作都直接針對硬碟),Python會將檔案內容存放到緩衝區(記憶體中),從而是程式啟動並執行的更快,這時,只有使用 flush 或者 close 時才會將緩衝區中的資料更新到硬碟中。

2.檔案的讀寫

2.1寫入檔案

#!/usr/bin/python#-*- coding:UTF-8 -*-#開啟檔案f = open(r‘D:\python\File\Pra_1.txt‘,‘w‘)try :     #寫入檔案     f.write(‘My name is OLIVER‘)finally:     #關閉檔案      f.close()

2.2讀取檔案

#!/usr/bin/python#-*- coding:UTF-8 -*-f = open(r‘D:\python\File\Pra_1.txt‘,‘r‘)print(f.read())f.close()

3.檔案特殊讀取

3.1遍曆每個字元,一次讀取

方法一:

#!/usr/bin/python#-*- coding:UTF-8 -*-f = open(r‘D:\python\File\Pra_1.txt‘,‘r‘)char = f.read(1)while char:    print(char)    char = f.read(1)f.close()

方法二:

#!/usr/bin/python#-*- coding:UTF-8 -*-f = open(r‘D:\python\File\Pra_1.txt‘,‘r‘)while True:    line = f.read(1)    if not line:break    print(line)f.close()

3.2遍曆每一行讀取

Pra_2.txt檔案內容:

 

#!/usr/bin/python#-*- coding:UTF-8 -*-f = open(r‘D:\python\File\Pra_2.txt‘,‘r‘)while True:    line = f.readline()    if not line:break    print(line)f.close()

 讀取結果:

 

Python 檔案I/O

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.