[Python Study Notes]檔案操作

來源:互聯網
上載者:User

標籤:att   刪除   with   nbsp   note   iso   class   檔案   int   

                      檔案操作                                                                         對檔案操作流程
  1. 開啟檔案,可添加filepath開啟某絕對路徑下的檔案,得到檔案控制代碼並賦值給一個變數
  2. 通過控制代碼對檔案進行操作
  3. 關閉檔案
 1 # The_author = ‘liu66‘ 2 # -*- coding = utf-8 -*- 3  4 filepath=‘D:\學習資料\ehmatthes-pcc-6bfeca0\chapter_10\pi_digits.txt‘ 5  6 read_sting = ‘‘ 7  8 with open(filepath) as file_object: 9     #contents=file_object.read()10     # print(contents)11     # ‘‘‘刪除末尾空行‘‘‘12     # print(contents.rstrip())13 14     ‘‘‘逐行列印‘‘‘15     for line in file_object:16     #     ‘‘‘兩行空白,一行來自檔案,一行來自print‘‘‘17     #     print(line)18     #     ‘‘‘去掉檔案換行‘‘‘19         # print(line.rstrip())20 21         ‘‘‘刪除所有空格‘‘‘22         read_sting+=line.strip()23 file_object.close()24 print(read_sting)25 print(len(read_sting))
  開啟檔案的模式有:
  • r,唯讀模式(預設)。
  • w,唯寫模式。【不可讀;不存在則建立;存在則刪除內容;】
  • a,追加模式。【可讀;   不存在則建立;存在則只追加內容;】

 

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

  • r+,可讀寫檔案。【可讀;可寫;可追加】
  • w+,寫讀
  • a+,同a

 

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

  • rU
  • r+U

 

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

  • rb
  • wb
  • ab

[Python Study Notes]檔案操作

聯繫我們

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