99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python編程中的文件讀寫及相關(guān)的文件對象方法講解
Python編程中的文件讀寫及相關(guān)的文件對象方法講解
2018-06-19
收藏

Python編程中的文件讀寫及相關(guān)的文件對象方法講解

python文件讀寫
python 進行文件讀寫的內(nèi)建函數(shù)是open或file
file_hander(文件句柄或者叫做對象)= open(filename,mode)
mode:
模式    說明
r        只讀
r+      讀寫
w       寫入,先刪除源文件,在重新寫入,如果文件沒有則創(chuàng)建
w+     讀寫,先刪除源文件,在重新寫入,如果文件沒有則創(chuàng)建(可以寫入寫出)
讀文件:    
>>> fo = open("/root/a.txt")
>>> fo    
<open file '/root/a.txt', mode 'r' at 0x7f5095dec4e0>    
>>> fo.read()    
'hello davehe\ni am emily\nemily emily\n'    
>>> fo.close()
>>> fo.read()                     #對象已關(guān)閉,在讀取就讀不到    
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file    
>>> f1 = file("/root/a.txt")         
>>> f1.read()    
'hello davehe\ni am emily\nemily emily\n'
    
>>> f1.close()

寫文件:    
root@10.1.6.200:~# ls -l new.txt    
ls: cannot access new.txt: No such file or directory    
>>> fnew = open("/root/new.txt",'w')  w參數(shù)文件沒有則創(chuàng)建
>>> fnew.write('hello \n i am dave')

這時查看文件數(shù)據(jù)其實還只是在緩存區(qū)中,沒有真正落到文件上.    
root@10.1.6.200:~# cat new.txt
root@10.1.6.200:~#

只要我把文件關(guān)閉,數(shù)據(jù)會從緩存區(qū)寫到文件里    
>>> fnew.close()
root@10.1.6.200:~# cat new.txt     
hello
i am dave

再次使用w參數(shù),文件會被清空,所以用該參數(shù)需要謹慎.    
>>> fnew = open("/root/new.txt","w")    
root@10.1.6.200:~# cat new.txt
root@10.1.6.200:~#

mode使用r+參數(shù):    
>>> fnew = open("/root/new.txt",'r+')
>>> fnew.read()    
'hello dave'    
>>> fnew.write('i am dave')
>>> fnew.close()    
root@10.1.6.200:~# cat new.txt     
hello davei am dave

這次打開文件,直接寫入,會發(fā)現(xiàn)ooo替換開頭字母,因為上面讀取操作使用了指針在寫就寫在后面.而這次是直接從頭寫入.    
>>> fnew = open("/root/new.txt",'r+')
>>> fnew.write('ooo')
>>> fnew.close()    
root@10.1.6.200:~# cat new.txt     
ooolo davei am dave

文件對象方法
下面文件對象方法

    FileObject.close()
    String=FileObject.readline([size])
    List = FileObject.readlines([size])
    String = FileObject.read([size])   read:讀取所有數(shù)據(jù)
    FileObject.next()          
    FileObject.write(string)
    FileObject.writelines(List)
    FlieObject.seek(偏移量,選項)
    FlieObject.flush() 提交更新    
>>> for i in open("/root/a.txt"):  用open可以返回迭代類型的變量,可以逐行讀取數(shù)據(jù)
...   print i
...     
hello davehe
i am emily
emily emily

FileObject.readline: 每次讀取文件的一行,size是指每行每次讀取size個字節(jié),直到行的末尾,超出范圍會讀取空字符串    
>>> f1 = open("/root/a.txt")
>>> f1.readline()    
'hello davehe\n'    
>>> f1.readline()    
'i am emily\n'    
>>> f1.readline()    
'emily emily\n'    
>>> f1.readline()
''
>>> f1.readline()
''
>>>f1.close()

 FileObject.readlines:返回一個列表    
>>> f1 = open("/root/a.txt")
>>> f1.readlines()    
['hello davehe\n', 'i am emily\n', 'emily emily\n']''

FileObject.next:返回當(dāng)前行,并將文件指針到下一行,超出范圍會給予警示,停止迭代.    
>>> f1 = open("/root/a.txt")
>>> f1.next()    
'hello davehe\n'    
>>> f1.next()    
'i am emily\n'    
>>> f1.next()    
'emily emily\n'    
>>> f1.next()    
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
StopIteration

FileObject.write:write和后面writelines在寫入前會是否清除文件中原來所有的數(shù)據(jù),在重新寫入新的內(nèi)容,取決于打開文件的模式.

FileObject.writelines(List):多行寫,效率比write高,速度更快,少量寫入可以使用write    
>>> l = ["python\n","python\n","python\n"]
>>> f1 = open('/root/a.txt','a')
>>> f1.writelines(l)
>>> f1.close()    
root@10.1.6.200:~# cat a.txt     
hello davehe
i am emily
emily emily
python
python
python

FlieObject.seek(偏移量,選項):可以在文件中移動文件指針到不同的位置.

位置的默認值為0,代表從文件開頭算起(即絕對偏移量),1代表從當(dāng)前位置算起,2代表從文件末尾算起.    
>>> f1 = open('/root/a.txt','r+')
>>> f1.read()    
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'    
>>> f1.seek(0,0)   指針指到開頭,在讀
>>> f1.read()    
'hello davehe\ni am emily\nemily emily\npython\npython\npython\n'    
>>> f1.read()
''
>>> f1.seek(0,0)
>>> f1.seek(0,2)   指針指到末尾,在讀
>>> f1.read()
''
下面看個小實例,查找a.txt中emily出現(xiàn)幾次    
root@10.1.6.200:~# vim file.py     
#!/usr/bin/env python
import re
f1 = open('/root/a.txt')
count = 0
for s in f1.readlines():
  li = re.findall("emily",s)
  if len(li) > 0:
    count = count + len(li)
print "this is have %d emily" % count
f1.close()    
root@10.1.6.200:~# cat a.txt     
hello davehe
i am emily
emily emily    
root@10.1.6.200:~# python file.py     
this is have 3 emily

數(shù)據(jù)分析咨詢請掃描二維碼

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

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }