Python之檔案操作

來源:互聯網
上載者:User

標籤:保留   刪除   計算   開啟檔案   位元組   windows   文本   位置   建立   

一,檔案操作基本流程

電腦系統分為:電腦硬體,作業系統,應用程式三部分。

我們用python或其他語言編寫的應用程式若想要把資料永久儲存下來,必須要儲存於硬碟中,這就涉及到應用程式要操作硬體,眾所周知,應用程式是無法直接操作硬體的,這就用到了作業系統。作業系統把複雜的硬體操作封裝成簡單的介面給使用者/應用程式使用,其中檔案就是作業系統提供給應用程式來操作硬碟虛擬概念,使用者或應用程式通過操作檔案,可以將自己的資料永久儲存下來。

有了檔案的概念,我們無需再去考慮操作硬碟的細節,只需要關注操作檔案的流程:

#1. 開啟檔案,得到檔案控制代碼並賦值給一個變數f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) #預設開啟模式就為r#2. 通過控制代碼對檔案進行操作data=f.read()#3. 關閉檔案f.close()

 可能出現的錯誤:

1.UnicodeDecodeError:檔案儲存體和開啟的方式不一樣

2:路徑中含有\t,\n時需要在路徑之前添加r或者用\\轉義

二,檔案編碼

f=open(...)是由作業系統開啟檔案,那麼如果我們沒有為open指定編碼,那麼開啟檔案的預設編碼很明顯是作業系統說了算了,作業系統會用自己的預設編碼去開啟檔案,在windows下是gbk,在linux下是utf-8

#這就用到了字元編碼的知識:若要保證不亂碼,檔案以什麼方式存的,就要以什麼方式開啟。f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)
三,檔案的開啟模式

檔案控制代碼 = open(‘檔案路徑’,‘模式’)

E:\\new.txt 絕對路徑
相對路徑:同一個檔案夾下的檔案就是相對路徑

r ,唯讀模式【預設模式,檔案必須存在,不存在則拋出異常】

rb,一般用在非文字類型的檔案:圖片,視頻  

  檔案的下載和上傳的功能用b模式

r+,讀寫(先讀,後寫 ) r+b

 

f = open(‘e:\建立文字文件.txt‘,‘r+‘,encoding = ‘utf-8‘)print(f.read())f.write(‘asdadd‘)f.close()

五種讀模數式:

1、f.read() 全部讀出來

f = open(‘log‘,mode=‘r‘,encoding=‘utf-8‘)content = f.read(3) # r 模式:n 是按照字元讀取print(content)f.close()
f = open(‘log‘,mode=‘rb‘)content = f.read(5) # rb 模式:n 是按照位元組讀取print(content)f.close()# bytes ---> strs = b‘\xe4\xb8\xb0\xe5\x8e‘.decode(‘utf-8‘)print(s)

 

2、f.readline() 按行讀

f = open(‘log‘,encoding=‘utf-8‘)line = f.readline()print(line)line1 = f.readline()print(line1)f.close()

 

3、f.readlines() 每一行作為一個元素放在列表中

f = open(‘log‘,encoding=‘utf-8‘)lines = f.readlines()print(lines)f.close()

 

4、 推薦方式:迴圈讀取

f = open(‘log‘,encoding=‘utf-8‘)for i in f:    print(i)f.close()

 

5、f.read(n)

r模式按照字元的數目讀取

rb模式按照位元組的數目讀取

f = open(‘e:\建立文字文件.txt‘,‘r‘,encoding = ‘gbk‘)content = f.read(3)print(content)f.close()

補充:bytes-->str  一個漢字3個位元組,4,5個會報錯

s = b‘\xe4\xb8\xb0.decode(‘‘utf - 8‘)  print(s)  #豐

 

f.write(‘laozhang‘)  若果沒有檔案,則建立檔案寫內容,如果有檔案則將原檔案刪除,再寫。

f = open(‘log‘,‘w‘,encoding=‘utf-8‘)f.write(‘laozhang是sb‘)f.close()f = open(‘log1‘,‘w‘,encoding=‘utf-8‘)f.write(‘laozhang依然是sb‘)f.close()

 

wb模式  需要將寫入的字串.encode轉換成二進位,並添加編碼

寫讀w+  先寫後讀,f.seek(0)游標移動到開頭

f = open(‘log1‘,‘wb‘)f.write(‘laozhang依然是sb‘.encode(‘utf-8‘))f.close()

 

追加

只追加 a ab

f = open(‘e:\建立文字文件.txt‘,‘a‘,encoding = ‘gbk‘)f.write(‘3‘)f.close()

 

斷點續傳用到了tell和seek,都是按照位元組去調整游標位置。

.truncate截取,按照位元組去截取。

with open(‘log‘,‘r‘,encoding = ‘utf-8‘) as f1:

  print(f1.read())

方法匯總:

def close(self, *args, **kwargs): # real signature unknown        關閉檔案        pass    def fileno(self, *args, **kwargs): # real signature unknown        檔案描述符          pass    def flush(self, *args, **kwargs): # real signature unknown        重新整理檔案內部緩衝區        pass    def isatty(self, *args, **kwargs): # real signature unknown        判斷檔案是否是同意tty裝置        pass    def read(self, *args, **kwargs): # real signature unknown        讀取指定位元組資料        pass    def readable(self, *args, **kwargs): # real signature unknown        是否可讀        pass    def readline(self, *args, **kwargs): # real signature unknown        僅讀取一行資料        pass    def seek(self, *args, **kwargs): # real signature unknown        指定檔案中指標位置        pass    def seekable(self, *args, **kwargs): # real signature unknown        指標是否可操作        pass    def tell(self, *args, **kwargs): # real signature unknown        擷取指標位置        pass    def truncate(self, *args, **kwargs): # real signature unknown        截斷資料,僅保留指定之前資料        pass    def writable(self, *args, **kwargs): # real signature unknown        是否可寫        pass    def write(self, *args, **kwargs): # real signature unknown        寫內容        pass

常用方法:

read  readable readline readlines for迴圈

seek tell write writeable

 

 改動檔案:

# 1,建立一個新檔案.# 2,讀取原檔案.import oswith open(‘log‘,encoding=‘utf-8‘) as f1,    open(‘log.bak‘,‘w‘,encoding=‘utf-8‘) as f2:    # 3,將原檔案的內容通過你想要的方式變更,並寫入新檔案件.    old_content = f1.read()    new_content = old_content.replace(‘alex‘,‘SB‘)    f2.write(new_content)#4,將原檔案刪除.os.remove(‘log‘)#5,將新檔案重新命名原檔案名稱.os.rename(‘log.bak‘,‘log‘)

 

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.