Python open 讀寫檔案實現指令碼代碼展示

來源:互聯網
上載者:User
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')#第二個參數預設為rinput = 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一次性寫入要高。

聯繫我們

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