1. 程式人生 > >【Python】讀寫檔案的操作

【Python】讀寫檔案的操作

程式語言中,我們經常會和檔案和資料夾打交道,這篇文章主要講的是Python中,讀寫檔案的常用操作:

一、開啟檔案

openFile = open('../Files/exampleFile.txt', 'a')

說明:
1. 第一個引數是檔名稱,包括路徑,可以是相對路徑./,也可以是絕對路徑"d:\test.txt";
2. 第二個引數是開啟的模式mode,包含r,w,a,r+

'r':只讀(預設。如果檔案不存在,則丟擲錯誤)

FileNotFoundError: [Errno 2] No such file or directory: '../Files/exampleFile.txt'
'w':只寫(如果檔案不存在,則自動建立檔案),檔案常用w
'a':附加到檔案末尾(如果檔案不存在,則自動建立檔案)
'r+':讀寫(如果檔案不存在,則丟擲錯誤)
FileNotFoundError: [Errno 2] No such file or directory: '../Files/exampleFile.txt'
如果需要以二進位制方式開啟檔案,需要在mode後面加上字元"b",比如"rb""wb"等,圖片常用wb

二、讀取內容
1. openFile.read(size)  
引數size表示讀取的數量,可以省略。如果省略size引數,則表示讀取檔案所有內容。
2. openFile.readline()
讀取檔案一行的內容
3. openFile.readlines()
讀取所有的行到數組裡面[line1,line2,...lineN]。在避免將所有檔案內容載入到記憶體中,這種方法常常使用,便於提高效率。
如果要顯示檔案內容,需要通過print進行列印:print(openFile.readline())

三、寫入檔案
1. openFile.write('Sample\n') 
將一個字串寫入檔案,如果寫入結束,必須在字串後面加上"\n",然後openFile.close()關閉檔案
如果需要追加內容,需要在開啟檔案時通過引數'a',附加到檔案末尾;如果覆蓋內容,通過引數'w'覆蓋

四、檔案中的內容定位
1.openFile.read()
讀取內容後文件指標到達檔案的末尾,如果再來一次openFile.readline()將會發現讀取的是空內容,
如果想再次讀取第一行,必須將定位指標移動到檔案開始位置:
2.openFile.seek(0) 
這個函式的格式如下(單位是bytes):openFile.seek(offset, from_what) 
from_what表示開始讀取的位置,offset表示從from_what再移動一定量的距離,
比如openFile.seek(28,0)表示定位到第0個字元並再後移28個字元。from_what值為0時表示檔案的開始,它也可以省略,預設是0即檔案開頭。 

五、關閉檔案釋放資源
1.openFile.close()
檔案操作完畢,一定要記得關閉檔案f.close(),可以釋放資源供其他程式使用

六、將讀取的內容寫入檔案
open('../Files/File.txt', 'a').write(openFile.read())
將讀取到的內容獲取我們需要的存入到另外一個檔案
我們一般的檔案操作步驟是:

1.開啟檔案>讀取檔案>關閉檔案

openFile = open('../Files/exampleFile.txt', 'r')
print("讀取所有內容:\n"+openFile.read())
openFile.seek(0)
print("讀取第一行內容:\n"+openFile.readline())
openFile.seek(28,0)
print("讀取開始位置向後移動28個字元後的內容:"+openFile.read())
openFile.close()

2.開啟檔案>寫入檔案>關閉檔案

openFile = open('../Files/exampleFile.txt', 'a')
openFile.write('Sample\n')
openFile.close()

3.開啟檔案>讀取檔案>讀取的檔案寫入到新檔案>關閉檔案

openFile = open('../Files/exampleFile.txt', 'r')
print("讀取所有內容:\n"+openFile.read())
openFile.seek(0)
print("讀取第一行內容:\n"+openFile.readline())
openFile.seek(28,0)
print("讀取開始位置向後移動28個字元後的內容:"+openFile.read())
openFile.seek(0)
open('../Files/File.txt', 'a').write(openFile.read())
openFile.close()

# 操作完檔案後一定要記得關閉,釋放記憶體資源