詳解使用Python檔操作open讀寫檔追加文字內容實例

高洛峰
發布: 2017-03-24 17:55:39
原創
2517 人瀏覽過

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.txt', 'w')
寫二進位檔案output = open('data.txt', 'wb')
追加寫檔案output = open('data.txt', 'a')

output .write("\n都有是好人")
output .close( )
登入後複製


寫入資料file_object = open('thefile.txt', 'w')

file_object.write(all_the_text)
file_object.close( )
登入後複製

以上是詳解使用Python檔操作open讀寫檔追加文字內容實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!