編程語言中,我們經常會和文件和文件夾打交道,這篇文章主要講的是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()
# 操作完文件后一定要記得關閉,釋放內存資源
---------------------
作者:cacho_37967865
來源:CSDN
原文:https://blog.csdn.net/sinat_37967865/article/details/79336884
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!