Python open詳解

來源:互聯網
上載者:User

標籤:並儲存   查看   trunc   inux   預設   run   win   發送   進位   

一、開啟檔案的模式有:

  1、r,唯讀模式【預設】。

  2、w,唯寫模式。【不可讀,不存在則建立,存在則刪除內容】

  3、a,追加模式。【可讀,不存在則建立,存在則只追加內容】

二、+ 表示可以同時讀寫某個檔案

  1、r + ,可讀寫檔案。【可讀,可寫,可追加】

  2、w+,寫讀

  3、a+ 同a

三、"U"表示在讀資料時,可以將\r \n \r\n自動轉換成\n(與r 或r+ 模式同時使用)

  rU

  r+U

四、"b" 表示處理二進位檔案(如:FTP發送上傳ISO鏡像檔案,linux可忽略,windows處理二進位時需要標註)

  rb

  wb

  ab

五、read 按照字元讀

#read 指定讀取字元
f = open(‘test.log‘,‘r‘,encoding=‘utf-8‘)
ret = f.read(2)#按照2個字元讀,python2中為按照2個位元組讀。
f.close()
print(ret)

六、tell
#tell 指標在某個位元組處
f = open(‘test.log‘,‘r‘,encoding=‘utf-8‘)
print(f.tell())#查看當前指標位置
f.read(2)
print(f.tell())
ret = f.read(2)#按照2個字元讀,python2中為按照2個位元組讀。
f.close()

七、seek
#seek
f = open(‘test.log‘,‘r‘,encoding=‘utf-8‘)
f.seek(1)#指定當前指標位置。
f.read()
f.close()
print(ret)
八、f.truncate

     檔案test.log開始的內容為:abcdefg

f = open(‘test.log‘,‘r+‘,encoding=‘utf-8‘)
f.seek(3)
f.truncate()#截取游標前面的內容並儲存到原檔案
f.close()
    此時檔案的內容變為:abc

Python open詳解

相關文章

聯繫我們

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