1. 程式人生 > >python 學習筆記 【file】

python 學習筆記 【file】

一、檔案 file

通常建議用內建函式 open() 開啟檔案,file 用於型別判斷。

>>> with open("test.txt", "w") as f:
...     print isinstance(f, file)   // 型別判斷
...     f.writelines(map(str, range(10)))

True

File Object 實現了上下文協議,可確保檔案被及時關閉。實際上,檔案物件被回收時總是會呼叫 close 方法,所以可以寫下面這樣的程式碼。

>>> open("test.txt", "r").read()
'0123456789'

如果要把資料寫到磁碟上,除呼叫 flush() 外,還得用 sync(),以確保資料從系統緩衝區同步到磁碟。close() 總是會呼叫這兩個方法。

開啟模式:

  • r: 只讀。
  • w: 只寫。已存在檔案將被清除 (truncate)。
  • a: 新增。總是新增到檔案尾部。
  • b: 二進位制模式。
  • r+: 更新檔案,可讀寫,不會截短檔案。
  • w+: 更新檔案,可讀寫,清除原有內容。
  • a+: 更新檔案,可讀寫,總是在尾部新增。

檔案物件還實現了迭代器協議,可直接迴圈獲取其內容。

>>> with open("main.py", "r") as f:
...     for line in f: print line
...

讀方法總能判斷不同平臺的換行標記,但寫方法不會新增任何換行字元,包括 writelines。

>>> with open("test.txt", "w") as f:
...     f.write("a")
...     f.writelines("bc")

>>> cat test.txt
abc

如必須按不同平臺寫入換行標記,可使用 os.linesep。

>>> os.linesep
'\n'

字串本身就是序列型別,可以直接用 writelines(str)。readline() 會返回包括換行符在內的整個行資料。通常建議用迭代器或 xreadlines() 代替 readlines(),後者預設一次性讀取整個檔案。

 

二、讀取二進位制檔案

讀取二進位制檔案使用 'rb' 模式。

這裡以圖片為例:

with open('test.png', 'rb') as f:
    image_data = f.read()    # image_data 是位元組字串格式的,而不是文字字串

這裡需要注意的是,在讀取二進位制資料時,返回的資料是位元組字串格式的,而不是文字字串。一般情況下,我們可能會對它進行編碼,比如 base64 編碼,可以這樣做:

import base64

with open('test.png', 'rb') as f:
    image_data = f.read()
    base64_data = base64.b64encode(image_data)    # 使用 base64 編碼
    print base64_data

下面是執行結果的一部分:

iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAACGFjVEw

三、寫入二進位制檔案

寫入二進位制檔案使用 'wb' 模式。

以圖片為例:

with open('test.png', 'rb') as f:
    image_data = f.read()

with open('/Users/ethan/test2.png', 'wb') as f:
    f.write(image_data)