【Python】-- 檔案操作

來源:互聯網
上載者:User

標籤:讀取   ade   class   sleep   open   print   close   建立   file   

 #檔案操作    檔案操作模式    r:唯讀        f = open("小重山","r",encoding="utf-8")        f.read() #按字元讀                f.readline() #按行讀取,游標發生位置變化,讀取的最後位置        f.readline()                f.readlines() #讀取全部檔案,游標發生位置變化,讀取的最後位置    w:唯寫        f = open("小重山","w",encoding="utf-8")        f.write()  #先清空檔案再寫    a:追加        f = open("小重山","a",encoding="utf-8")        f.append("hah ") #預設寫到最後,游標在最後,不清空內容         f.close()  #open 和 close成對出現,開啟再關閉,不關閉資料存在緩衝裡        truncate(): #截斷資料        r模式:無法截斷,唯讀模式        w模式: 先清空,清空後沒內容,截斷無效        a模式:截斷指定位置後的內容        r+: 讀寫入模式        先讀,讀取完成後再寫,游標預設在0位置,最後位置開始寫    w+: 寫讀模式        先清空檔案再寫,寫完可讀取    a+: 追加讀模數式        先追加內容,然後可以讀取,游標預設在最後位置        with:   #同時管理多個檔案對象            with open("file1","r") as f_read,open("file2","w") as f_write:        【例子】#迭代器number = 0for i in f: #將f做成一個迭代器,用一行取一行取完為止    number += 1    if number == 6:        i = "".join([i.strip(),"xinjiadeneirong"]) #取代加號        print(i.strip())    print(i.strip())#最佳化版number = 0for i in f :    if number == 6:        i = "".join([i.strip(),‘xinjiadeneirong‘])    print(i.strip())        #進度條import sys,timefor i in range(30):    sys.stdout.write("*")     sys.stdout.flush() #即時儲存到硬碟    time.sleep(0.1)  #等待0.1秒返回執行結果#如何在磁碟修改檔案    #常規思路,儲存機制限制    number = 0     for line in f:        number +=1        if number == 3:            f.while(‘alex‘) #只是先寫到緩衝裡,不能實現在硬碟讀寫                #再建立一個檔案,一個讀,一個寫    with open("小重山","r",encoding="utf-8") as f_read,open("小重山2","w",encoding="utf-8")        number = 0     for line in f_read:        number += 1        if number == 5:            line="".join([line.strip(),"alex\n"])        f_write.write(line)

 

 

【Python】-- 檔案操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.