首頁  >  文章  >  後端開發  >  Python open 讀寫檔案實作腳本程式碼展示

Python open 讀寫檔案實作腳本程式碼展示

巴扎黑
巴扎黑原創
2017-05-21 18:54:021617瀏覽

Python中檔案操作可以通過open函數,這的確很像C語言中的fopen。透過open函數取得一個file object,然後呼叫read(),write()等方法對檔案進行讀寫操作。

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一次寫入要高。

以上是Python open 讀寫檔案實作腳本程式碼展示的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn