Python 檔案操作

來源:互聯網
上載者:User

標籤:重新整理   終端   整型   als   seek   for   \n   轉換   需要   

1.  open()  file.close()
# 關閉後的檔案不能再進行讀寫操作,否則會觸發ValueErrorfo = open(‘a.txt‘, ‘r‘)print(‘開啟a.txt的檔案‘)fo.close()

 

 

2.  flush()
# flush()用來重新整理緩衝區,將緩衝區的資料立刻寫入檔案# 同時清空緩衝區,不需要是被動的等待輸出緩衝區寫入# 一般情況,檔案關閉後會自動重新整理緩衝區,但有時需要在關閉前重新整理它,這時就需要使用flush()方法fo =open(‘a.txt‘, ‘wb‘)print(‘開啟a.txt的檔案‘)fo.flush()fo.close()

 

 

3.  開啟檔案的模式

  ①. 唯讀模式 r (預設)

  ②. 唯寫模式 w (不可讀,不存在則建立,存在則覆蓋)

  ③. 追加模式 a (可讀,不存在則建立,存在則只追加內容)

  ④. ‘+‘ 表示可同時讀寫某個檔案:

    r+ 可讀寫檔案(可讀、可寫、可追加)

    w+ 寫讀

    a+ 追加

  ⑤. ‘u’表示在讀取時,可將 \r \n  \r\n  自動轉換成 \n (與 r 或者 r+ 模式同時使用)

   因為Windows系統的分行符號為\r\n,Linux系統的分行符號為 \n , 加上u則能自動把\r\n轉換成\n

    ru

    r+u

  ⑥. ‘b’ 表示處理二進位檔案

    rb

    wb

    ab

 

4.
# # 讀取檔案內容(可指定每次讀取字元數)# with open(‘a.txt‘, ‘r+‘, encoding=‘utf-8‘) as f:#     ret = f.read(8)#     print(ret)

 

 

5.
# 讀取資料(可指定讀取字元數),存為list顯示# f = open(‘b.txt‘, ‘r+‘, encoding=‘utf-8‘)# ret = f.readlines()# print(ret)# f.close()

 

 

6.
# # 讀取一行資料# f = open(‘b.txt‘, ‘r+‘, encoding=‘utf-8‘)# ret = f.readline()# print(ret)# f.close()

 

 

7.
# 判斷檔案是否可讀(不可讀則報錯“No such file or directory:”)f = open(‘b.txt‘, ‘r+‘, encoding=‘utf-8‘)ret = f.readable()print(ret)f.close()

 

 

8.
# 擷取指標位置f = open(‘b.txt‘, ‘r+‘, encoding=‘utf-8‘)# 先讀取8個字元ret = f.read(8)# 查看當前指標位置print(‘pointer position: %s‘ %f.tell())print(ret)# 重設指標到起始位f.seek(0)# 查看指標當前位置print(‘pointer position: %s‘ %f.tell())f.close()

 

 

9.
# 指定檔案中指標位置f = open(‘b.txt‘, ‘r+‘, encoding=‘utf-8‘)# 先讀取8個字元ret = f.read(8)print(ret)# 重設指標到起始位f.seek(0)# 在重新讀取8個字元ret = f.read(8)print(ret)f.close()

 

 

10.
# 截取檔案資料,僅保留指定之前資料(指定位元組數)f = open(‘b.txt‘, ‘r+‘, encoding=‘utf-8‘)# 檔案只保留前8個位元組資料,檔案後面的資料全部刪除f.truncate(8)ret = f.read()print(ret)f.close()

 

 

11.  fileno()
# fileno()返回一個整型的檔案描述(file desccriotor FD 整型)# 可用於底層作業系統的I/O操作fo = open(‘b.txt‘, ‘wb‘)print(‘檔案名稱為:‘,fo.name)fid = fo.fileno()print(‘檔案描述為:‘,fid)fo.close()

 

 

12.  isatty()
# isatty()檢測檔案是否串連到一個終端裝置# 如果是返回True,否則返回Falsefo = open(‘b.txt‘, ‘wb‘)print(‘檔案名稱為:‘,fo.name)ret = fo.isatty()print(‘傳回值:‘,ret)fo.close()

 

 

13.  next()
# Python3中的file對象不支援next()方法# Python3的內建函數next()通過迭代器調用__next()__方法返回下一項# 在迴圈中,next()方法會在迴圈中調用,該方法返迴文件的下一行# 如果到達結尾(EOF)則觸發Stopiterationfo = open(‘b.txt‘, ‘r‘)for index in range(5):    line = next(fo)    print(‘第%d行 - %s‘%(index, 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.