新聞中心
在Python open讀寫文件實(shí)現(xiàn)腳本

成都地區(qū)優(yōu)秀IDC服務(wù)器托管提供商(成都創(chuàng)新互聯(lián)公司).為客戶提供專業(yè)的成都機(jī)柜租用,四川各地服務(wù)器托管,成都機(jī)柜租用、多線服務(wù)器托管.托管咨詢專線:028-86922220
在實(shí)際使用open打開相關(guān)文件之后一定要記得要調(diào)用文件對(duì)象的close()的相關(guān)方法。比如可以用try/finally語句來確保最后是否能關(guān)閉文件。以下就是文章的相關(guān)內(nèi)容的詳細(xì)接介紹,望你會(huì)有所收獲。
- file_object = open('thefile.txt')
- try:
- all_the_text = file_object.read( )
- finally:
- file_object.close( )
注:不能把open語句放在try塊里,因?yàn)楫?dāng)打開文件出現(xiàn)異常時(shí),文件對(duì)象file_object無法執(zhí)行close()方法。
讀文件
讀文本文件
- input = open('data', 'r')
以上的相關(guān)代碼就是Python open讀寫文件中實(shí)現(xiàn)腳本第二個(gè)參數(shù)默認(rèn)為r
- input = open('data')
讀二進(jìn)制文件
- input = open('data', 'rb')
讀取所有內(nèi)容
- file_object = open('thefile.txt')
- try:
- all_the_text = file_object.read( )
- finally:
- file_object.close( )
讀固定字節(jié)
- 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( )
以上就是對(duì)Python open讀寫文件實(shí)現(xiàn)腳本相關(guān)的內(nèi)容的部分介紹,望你會(huì)有所收獲。
標(biāo)題名稱:在Pythonopen讀寫文件實(shí)現(xiàn)腳本的詳細(xì)介紹
地址分享:http://m.5511xx.com/article/codsgsh.html


咨詢
建站咨詢
