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

熱線電話:13121318867

登錄
首頁精彩閱讀詳細(xì)講解Python中的文件I/O操作
詳細(xì)講解Python中的文件I/O操作
2017-08-11
收藏

詳細(xì)講解Python中的文件I/O操作

本章將覆蓋所有在Python中使用的基本I/O功能。有關(guān)更多函數(shù),請參考標(biāo)準(zhǔn)Python文檔。

打印到屏幕上:

產(chǎn)生輸出最簡單的方法是使用print語句,可以通過用逗號分隔的零個或多個表達(dá)式。該函數(shù)將傳遞到一個字符串表達(dá)式,并將結(jié)果寫到標(biāo)準(zhǔn)輸出,如下所示: 

#!/usr/bin/python
 
print "Python is really a great language,", "isn't it?";

這將產(chǎn)生結(jié)果輸出在標(biāo)準(zhǔn)屏幕上,結(jié)果如下:   
Python is really a great language, isn't it?

讀取鍵盤輸入:

Python提供了兩個內(nèi)置的函數(shù)來讀取一行,從標(biāo)準(zhǔn)輸入,默認(rèn)情況下是來自鍵盤的文本。這些函數(shù)包括:

        raw_input
        input

raw_input 函數(shù):

raw_input([prompt])函數(shù)從標(biāo)準(zhǔn)輸入讀取一行并返回一個字符串(去掉結(jié)尾的換行)。
#!/usr/bin/python
 
str = raw_input("Enter your input: ");
print "Received input is : ", str

這將提示您輸入字符串,它會在屏幕上顯示相同的字符串。當(dāng)輸入“Hello Python!”,它的輸出是這樣的:

Enter your input: Hello Python
Received input is : Hello Python

input函數(shù):

input([prompt]) 函數(shù)相當(dāng)于raw_input,只是它假設(shè)輸入的是一個有效的Python表達(dá)式,并返回計(jì)算結(jié)果。 
#!/usr/bin/python
 
str = input("Enter your input: ");
print "Received input is : ", str

對所輸入這將產(chǎn)生結(jié)果如下:

Enter your input: [x*5 for x in range(2,10,2)]
Recieved input is : [10, 20, 30, 40]

打開和關(guān)閉文件:

到現(xiàn)在為止,已經(jīng)了解讀取和寫入標(biāo)準(zhǔn)輸入和輸出?,F(xiàn)在,我們看看如何用實(shí)際數(shù)據(jù)文件。

Python提供了基本的函數(shù)和必要在默認(rèn)情況下對文件進(jìn)行操作的方法。可以使用一個文件對象file來做大部分文件操作。
open 函數(shù):

想要讀取或?qū)懭胛募仨毷褂肞ython內(nèi)置的open()函數(shù)來打開它。該函數(shù)創(chuàng)建一個文件對象,這將用來調(diào)用與之關(guān)聯(lián)的其他支持方式。
語法:
file object = open(file_name [, access_mode][, buffering])

下面是參數(shù)的詳細(xì)信息:

        file_name: file_name參數(shù)是一個字符串值,包含您要訪問的文件的名稱。
        access_mode: access_mode決定了文件必須被打開,即,讀,寫,追加等的可能值是下表中給定的一個完整的列表的模式。這是可選參數(shù),默認(rèn)文件存取方式為read (r)。
        buffering: 如果緩沖值被設(shè)置為0時,沒有緩沖將發(fā)生。如果該緩沖值是1,行緩沖會在訪問一個文件來執(zhí)行。如果指定的緩沖值為大于1的整數(shù),則緩沖作用將與所指示的緩沖區(qū)的大小進(jìn)行。如果為負(fù),則緩沖區(qū)的大小是系統(tǒng)默認(rèn)(默認(rèn)行為)。

這里是打開一個文件的不同模式的列表:

 file 對象屬性:

一旦文件被打開,文件對象可以得到有關(guān)該文件的各種信息。

下面是文件對象相關(guān)的所有屬性的列表:

例子:    
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

這將產(chǎn)生以下結(jié)果:    
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0

close() 方法:

一個文件對象的close()方法刷新未寫入的信息,并關(guān)閉該文件的對象,在這之后沒有數(shù)據(jù)內(nèi)容可以執(zhí)行寫入。

Python自動關(guān)閉,當(dāng)文件的引用對象被重新分配給另外一個文件。它是使用close()方法來關(guān)閉文件是一個很好的做法。
語法:
    
fileObject.close();

例子:
    
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
 
# Close opend file
fo.close()

這將產(chǎn)生以下結(jié)果:
    
Name of the file: foo.txt

讀取和寫入文件:

file對象提供了一組訪問方法。我們來看看如何使用read()和write()方法來讀取和寫入文件。
write() 方法:

write()方法寫入字符串到任何一個打開的文件。要注意的是Python字符串可以具有二進(jìn)制數(shù)據(jù),而不僅僅是文字。

write()方法不要將換行字符('\n')添加到字符串的結(jié)尾:
語法:
    
fileObject.write(string);

這里,傳遞的參數(shù)是要寫入到打開的文件的內(nèi)容。
例子
    
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
 
# Close opend file
fo.close()

上面的方法會創(chuàng)建 foo.txt 文件,并會將給定的內(nèi)容寫在該文件中,并最終將關(guān)閉該文件。
    
Python is a great language.
Yeah its great!!

read() 方法:

read()方法讀取一個打開的文件的字符串。要注意的是Python字符串可以具有二進(jìn)制數(shù)據(jù),而不僅僅是文本。
語法
?
1
    
fileObject.read([count]);

這里,傳遞的參數(shù)是從打開的文件中讀出的字節(jié)數(shù)。此方法從該文件的開頭讀取,如果計(jì)數(shù)丟失,那么它會嘗試盡可能多地讀取,直到文件的末尾。
例子:

這里以一個文件foo.txt作為例子,這是在上面創(chuàng)建的。
    
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

這將產(chǎn)生以下結(jié)果:    
Read String is : Python is

文件位置:

tell()方法告訴該文件中的當(dāng)前位置;換句話說,下一個讀取或?qū)懭雽l(fā)生在從該文件的開頭的字節(jié)數(shù)。

seek(offset[, from]) 方法會更改當(dāng)前的文件位置。偏移參數(shù)指示要移動的字節(jié)數(shù)。從該參數(shù)指定字節(jié)將被移至參考點(diǎn)。

如果from被設(shè)置為0,這意味著使用該文件的開始處作為基準(zhǔn)位置,設(shè)置為1則是使用當(dāng)前位置作為基準(zhǔn)位置,如果它被設(shè)置為2,則該文件的末尾將被作為基準(zhǔn)位置。
例子

讓我們以一個文件foo.txt,這是上面創(chuàng)建。
    
#!/usr/bin/python
 
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
 
# Check current position
position = fo.tell();
print "Current file position : ", position
 
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()

這將產(chǎn)生以下結(jié)果:
    
Read String is : Python is
Current file position : 10
Again read String is : Python is

重命名和刪除文件:

Python的os模塊提供了一些方法,可以幫助執(zhí)行文件處理操作,如重命名和刪除文件。

要使用這個模塊,需要先導(dǎo)入它,然后調(diào)用相關(guān)的功能。
rename() 方法:

rename()方法有兩個參數(shù),當(dāng)前文件名和新文件名。
語法:
    
os.rename(current_file_name, new_file_name)

例子

以下是例子來重命名文件test1.txt:
    
#!/usr/bin/python
import os
 
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )

remove() 方法:

可以使用remove()方法通過提供參數(shù)作為文件名稱作為要刪除的文件。
語法:    
os.remove(file_name)

例子

以下為示例刪除現(xiàn)有文件test2.txt:
    
#!/usr/bin/python
import os
 
# Delete file test2.txt
os.remove("text2.txt")

Python中的目錄:

所有的文件都包含不同的目錄中,而在Python中處理這些沒有問題。os模塊有幾種方法,可以幫助創(chuàng)建,刪除和更改目錄。
mkdir() 方法:

可以使用os模塊的mkdir()方法在當(dāng)前目錄下創(chuàng)建目錄。需要提供參數(shù),這個方法包含的目錄要創(chuàng)建的名稱。
語法:    
os.mkdir("newdir")

例子:

以下為示例在當(dāng)前目錄下創(chuàng)建test目錄如下所示:    
#!/usr/bin/python
import os
 
# Create a directory "test"
os.mkdir("test")

chdir() 方法:

可以使用chdir()方法來改變當(dāng)前目錄。chdir()方法接受一個參數(shù),那就是要成為當(dāng)前目錄的目錄的名稱。
語法:    
os.chdir("newdir")

例子:

下面是一個進(jìn)入“/home/newdir”目錄的例子:    
#!/usr/bin/python
import os
 
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")

getcwd() 方法:

getcwd()方法顯示當(dāng)前的工作目錄。
例子:    
os.getcwd()

例子:

以下是例子給定為當(dāng)前目錄:
    
#!/usr/bin/python
import os
 
# This would give location of the current directory
os.getcwd()

rmdir() 方法:

rmdir()命令方法刪除目錄,它是通過方法的參數(shù)。

在刪除一個目錄,它的所有內(nèi)容應(yīng)該被刪除。
語法:    
os.rmdir('dirname')

例子

下面是一個例子刪除“/tmp/test”目錄。它是必需的,得到的目錄完全的名稱,否則將搜索在當(dāng)前目錄中的目錄。
    
#!/usr/bin/python
import os
 
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )

數(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(), // 加隨機(jī)數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進(jìn)行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗(yàn)證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗(yàn)服務(wù)器是否宕機(jī) new_captcha: data.new_captcha, // 用于宕機(jī)時表示是新驗(yàn)證碼的宕機(jī) 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){ //倒計(jì)時完成 $(".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); }