熱線電話:13121318867

登錄
首頁精彩閱讀Python文件操作,open讀寫文件,追加文本內容實例
Python文件操作,open讀寫文件,追加文本內容實例
2017-11-26
收藏

Python文件操作,open讀寫文件,追加文本內容實例

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( )
以上就是本文的全部內容,希望對大家的學習有所幫助

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢