7.開啟檔案、檔案讀寫操作、with方式、檔案常用函數,

來源:互聯網
上載者:User

7.開啟檔案、檔案讀寫操作、with方式、檔案常用函數,
開啟檔案:

在python3中,開啟檔案的函數是:

open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
 
參數說明:
file--檔案名稱
mode—開啟模式,預設唯讀模式
buffering--如果buffering的值被設為0,就不會有寄存。如果buffering的值取1,訪問檔案時會寄存行。如果將buffering的值設為大於1的整數,表明了這就是的寄存區的緩衝大小。如果取負值,寄存區的緩衝大小則為系統預設。
encoding—開啟檔案的編碼方式 
模式介紹:

r:唯讀模式(預設)

w :唯寫模式,如果檔案不存在就建立,如果存在,寫入的資料會覆蓋原來的資料

b :二進位模式

t :文字模式

+:可寫可讀模式

a:追加模式,如果檔案存在則檔案指標指向檔案末尾(追加資料),如果不存在就建立

r+:讀追加模式,先讀,再追加

w+:寫讀模式,先寫,意味著原本內容丟失,再讀。

 

 

 

  • 如果對於含有非ascll字元的檔案,必須使用encoding,否則會拋異常:

print("r".center(50,'-'))f=open("file.txt",encoding="utf-8")print(f.read())f.close()-----------------運行結果:mysasaaafsafsa中文中文葫蘆娃

 

檔案使用完畢後必須關閉: 檔案指標.close()

 

檔案操作:

 

讀操作:

讀取檔案內容如下:

  • reads()是讀出全部內容
print("r".center(50,'-'))f=open("file.txt",encoding="utf-8")print(f.read())f.close()---------------------------運行結果:mysasaaafsafsa中文中文葫蘆娃
  • readline()是讀出一行
print("r".center(50,'-'))f=open("file.txt",encoding="utf-8")print(f.readline())f.close()-----------運行結果:my
  • readlines()是讀出全部內容,並整理成一個列表
print("r".center(50,'-'))f=open("file.txt",encoding="utf-8")print(f.readlines())f.close()------------------------r-------------------------運行結果:['my\n', 'sas\n', 'aaa\n', 'fsafsa\n', '中文\n', '中文\n', '葫蘆娃\n', '\n']

 

  • r+模式會根據讀的內容來決定指標的位置
print("r".center(50,'-'))f=open("file.txt","r+",encoding="utf-8")# print(f.readline())f.write("hello mike")f.close()

結果:

 

print("r".center(50,'-'))f=open("file.txt","r+",encoding="utf-8")print(f.readline())f.write("hello mike")f.close()

新結果:

 

 

 

 

寫操作:
  • write():將一個字串寫入檔案
myfile=open("myfile1","wb")myfile.write(b"nnnnnn")myfile.write("my葫蘆娃".encode("utf-8"))myfile.close()
  • writelines(可迭代對象) 將一個可迭代對象寫入檔案
myfile=open("myfile1","wb")myfile.write(b"nnnnnn")myfile.writelines([b'1',b'2',b'3',b'4'])myfile.close()
  • 當需要寫完之後即時讀出來時,使用w+,然後將檔案指標置迴文件頭:
myfile=open("myfile1","wb+")myfile.write(b"nnnnnn")myfile.seek(0)print(myfile.read())myfile.close()
      • 如果是需要讀出特定位置,可以使用變數來記錄位置
myfile=open("myfile1","wb+")myfile.write(b"1nnnnnn")site=myfile.tell()myfile.write(b"2nnnnnn")myfile.seek(site)##讀出後一段print(myfile.read())myfile.close()
with:
  • 為了便捷的關閉檔案,python增加了with功能,當with體執行完將自動關閉開啟的檔案:
with open("file.txt","r+",encoding="utf-8") as f:##將自動執行f.close()    print(f.tell())    f.write("金剛")    for line in f:        print(line,end="")
  • 可以同時開啟多個檔案:
with open("file.txt",'r') as f ,\open("file.new",'r') as m:    print(f.read(),m.read())
檔案常用函數:

file.close():關閉檔案。關閉後檔案不能再進行讀寫操作

 

file.seek(offset[, whence]):設定檔案當前位置

file.tell():返迴文件當前位置。

myfile=open("myfile1","wb+")myfile.write(b"1nnnnnn")site=myfile.tell()myfile.write(b"2nnnnnn")myfile.seek(site)##讀出後一段print(myfile.read())myfile.close()

file.flush():重新整理檔案內部緩衝,立即把內部緩衝區的資料寫入檔案,因為並不是馬上將檔案

import timemyfile=open("myfile1","wb+")myfile.write(b"1nnnnnn")time.sleep(10)# myfile.flush()myfile.write(b"2nnnnnn")myfile.close()

上述代碼,直到程式運行完成才一次性寫入“1nnnnnn2nnnnnn”

import timemyfile=open("myfile1","wb+")myfile.write(b"1nnnnnn")myfile.flush()time.sleep(10)myfile.write(b"2nnnnnn")myfile.close()

上述代碼,可以看到,在程式sleep之前就已經寫入了“1nnnnnn”

 

 

file.truncate([size]):截取檔案,從檔案開頭,截到指定位置,會覆蓋原檔案。

檔案內容:

print("r".center(50,'-'))f=open("file.txt","r+",encoding="utf-8")print(f.readline())print("----truncate()-------")print(f.tell())m=f.tell()f.truncate(m)#內容從0位置截斷到指定位置,不論當前游標位置f.close()

 

執行後,檔案內容:

聯繫我們

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