1.open

使用 open 開啟檔案後一定要記得呼叫檔案物件的 close() 方法。比如可以用 try/finally 語句來確保最後能關閉檔案。

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

注:不能把 open 語句放在 try 塊裡,因為當開啟檔案出現異常時,檔案物件 file_object 無法執行 close() 方法。

2. 讀檔案

讀文字檔案

input = open('data', 'r')
#第二個引數預設為 r
input = open('data')

讀二進位制檔案

input = open('data', 'rb')

讀取所有內容

file_object = open('thefile.txt')
try:
  all_the_text = file_object.read( )
finally:
  file_object.close( )

讀固定位元組

file_object = open('abinfile', 'rb')
try:
  while True:
    chunk = file_object.read(100)
    if not chunk:
      break
    do_something_with(chunk)
finally:
  file_object.close( )

讀每行

list_of_all_the_lines = file_object.readlines( )

如果檔案是文字檔案,還可以直接遍歷檔案物件獲取每行:

for line in file_object:
    process line

3. 寫檔案

寫文字檔案

output = open('data', 'w')

寫二進位制檔案

output = open('data', 'wb')

追加寫檔案

output = open('data', 'w+')

寫資料

file_object = open('thefile.txt', 'w')
file_object.write(all_the_text)
file_object.close( )

寫入多行

file_object.writelines(list_of_text_strings)

注意,呼叫 writelines 寫入多行在效能上會比使用 write 一次性寫入要高。