python 之 檔案I/0

來源:互聯網
上載者:User

標籤:position   對象   access   blog   txt   決定   若是   簡單   os模組   

開啟和關閉檔案

open()函數

必須要open()內建函數開啟一個檔案,建立一個file對象,相關的方法才可以調用它進行讀寫。

文法file object=open(file_name [,access_mode] [,buffering])
file_name:變數是一個包含了你要訪問的檔案名稱的字串值
access_mode:決定了開啟檔案的模式:唯讀,寫入,追加等,預設是唯讀 (R)
buffering:如果buffering的值被設為0,就不會寄存。如果buffering的值取值1,訪問檔案時會寄存行。
若是大於1,表明是寄存區的大小。
若是負值,則緩衝大小則為系統預設

File對象的屬性

檔案開啟後就存在一個file對象,可以得到關於檔案的各種資訊

實際簡單案例

fo = open("foo.txt", "wb")print "檔案名稱: ", fo.nameprint "是否已關閉 : ", fo.closedprint "訪問模式 : ", fo.mode
輸出:
檔案名稱: foo.txt
是否已關閉 : False
訪問模式 : wb

close()方法

文法:fileObject.close();案例:fo.close()

write()方法

文法:fileObject.write(string)案例:fo.open("foo.txt","wb")//會報錯,講wb改為 w+fo.write("www.runoob.com!\nVery good site!\n")fo.close()

read()方法

該方法從一個開啟的檔案中讀取一個字串,可以是位元據而不僅是文字

文法:fileObject.read([count])count:表示讀取的位元組,若是不寫則會儘可能讀取,與開啟檔案的緩衝大小有關
案例:
fo.open("foo.txt","r+")
str=fo.read(10)
print(str)
fo.close()

檔案定位

tell()方法:顯示檔案的當前位置。

seek(offset [,from])方法 改變當前檔案內的當前位置。offset變數表示要移動的位元組數。from變數指定開始移動位元組的參考位置

                from=0:以檔案的開頭這麼多位元組作為移動位元組的參考位置

                from=1:以當前位置作為參考位置

                from=2:將該檔案的末尾將作為參考位置

fo=open("foo.txt","r+")str=fo.read(10);print(str)#尋找當前位置position=fo.tell()print("當前檔案內位置:",position)position=fo.seek(4,0);str=fo.read(10);print("移動後的檔案內位置",str)position=fo.tell()print("移動後檔案內位置:",position)fo.close()輸出:www.runoob當前檔案內位置: 10移動後的檔案內位置 runoob.com當前檔案內位置: 14

重新命名和刪除檔案

python的os模組提供了檔案的處理方法,需要匯入該模組

os.rename()方法

文法:os.rename(current_file_name,new_file_name)案例:os.rename("foo.txt","test2.txt")

os.remove()方法

文法:os.remove(file_name)

 

python裡的目錄:

mkdir()方法:在目前的目錄下建立新的目錄檔案

文法:os.mkdir("newdir")案例:os.mkdir(“test”)

chdir()方法:用來改變當前的目錄

文法:os.chdir("newdir")案例:#將目前的目錄修改為/home/newidros.chdir("/home/newidr")

getcwd()方法:用來顯示當前的目錄

文法:os.getcwd()案例:print(os.getcwd())

rmdir()方法:用來刪除目錄

文法:os.rmdir(‘dirname‘)案例:刪除目錄/tmp/testos.rmdir("/tmp/test")

 

File對象:提供了操作檔案的方法

Os對象:提供了操作目錄的方法

                

                

 

python 之 檔案I/0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.