Python中的檔案物件?
在Python中,當我們嘗試讀取或寫入檔案時,不需要匯入任何庫,因為它是由系統原生處理的。
該open()函式開啟一個檔案並返回一個檔案物件。**檔案物件**包含方法和屬性,這些方法和屬性稍後可用於檢索資訊或操作已開啟的檔案。
檔案操作
檔案是磁碟上用於儲存相關資訊的命名位置,由於檔案具有名稱和位置,因此它儲存在硬碟中。在Python中,檔案操作按以下順序執行:
- 開啟檔案。
- 讀取或寫入操作。
- 關閉檔案。
使用'open()'函式開啟檔案
要同時開啟一個檔案進行讀取和寫入,必須使用內建的**open()**函式。**open()**函式使用兩個引數。第一個是檔名,第二個是模式(讀取或寫入)。在Python中開啟檔案物件的語法如下:
File_obj = open("filename", "mode")
Python檔案模式
開啟檔案後,可以指定檔案模式。例如,如果要將追加模式**"a"**新增到檔案,則寫入**"w"**或讀取**"r"**。此外,可以選擇以二進位制模式或文字格式開啟檔案。以下是open()函式支援的不同模式:
模式 | 描述 |
---|---|
‘r’ | 開啟檔案以進行讀取。(預設) |
‘w’ | 開啟檔案以進行寫入。如果檔案不存在,則建立一個新檔案;如果檔案存在,則截斷檔案。 |
‘x’ | 開啟檔案以進行獨佔建立。如果檔案已存在,則操作失敗。 |
‘a’ | 開啟以在檔案末尾追加,而不截斷它。如果檔案不存在,則建立一個新檔案。 |
‘t’ | 以文字模式開啟。(預設) |
‘b’ | 以二進位制模式開啟。 |
‘+’ | 開啟檔案以進行更新(讀取和寫入) |
建立文字檔案
讓我們使用任何文字編輯器在Python中建立一個簡單的文字檔案。在下面的示例中,將在當前工作目錄中建立一個新檔案,並在開啟新建立的檔案時。
# Create a text file named "textfile.txt" in your current working directory f = open("textfile.txt", "w") # above will create a file named textfile.txt in your default directory f.write("Hello, Python") f.write("\nThis is our first line") f.write("\nThis is our second line") f.write("\nWhy writing more?, Because we can :)") f.close()
輸出
讀取文字檔案
有多種方法可以在Python中讀取文字檔案,其中一些方法如下所示。
-
提取字串的所有字元
-
讀取一定數量的字元
-
逐行讀取檔案
-
遍歷檔案物件
-
分割文字檔案中的行
提取字串的所有字元
如果您想提取包含檔案中所有字元的字串,可以使用以下方法
file.read()
示例
下面是一個實現上述語法的程式
f = open("textfile.txt", "r") f.read()
輸出
'Hello, Python\nThis is our first line\nThis is our second line\nWhy writing more?, Because we can :)'
讀取一定數量的字元
如果您想從檔案中讀取字串中一定數量的字元,可以使用如下所示的方法:
f = open("textfile.txt", "r") print(f.read(13))
輸出
Hello, Python
逐行讀取檔案
但是,如果您想逐行讀取檔案,則可以使用readline()函式。
示例
f = open("textfile.txt", "r") print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline())
輸出
Hello, Python This is our first line This is our second line Why writing more?, Because we can :)
遍歷檔案物件
如果您想以最結構化和高效的方式讀取或返回檔案中的所有行,可以使用迴圈遍歷方法。
f = open("textfile.txt", "r") for line in f: print(line)
輸出
Hello, Python This is our first line This is our second line Why writing more?, Because we can :)
分割文字檔案中的行
我們可以使用Python的split()函式分割從文字檔案中獲取的行。我們可以使用任何你選擇的字元來分割文字,它可以是空格字元、冒號或其他字元。
with open("textfile.txt", "r") as f: data = f.readlines() for line in data: words = line.split() print(words)
輸出
['There', 'are', 'tons', 'to', 'reason', 'to', "'fall", 'in', 'love', 'with', "PYTHON'"] ['See,', 'i', 'have', 'added', 'one', 'more', 'line', ':).'] ['Hello,', 'Python-Here', 'i', 'come', 'once', 'again!']
寫入檔案
寫入檔案很簡單,您只需開啟檔案並傳遞要寫入檔案的文字即可。我們可以使用open()方法將資料追加到現有檔案中。使用EOL字元在寫入資料到檔案後開始新的一行。
示例
f = open("textfile.txt", "w") f.write("There are tons to reason to 'fall in love with PYTHON'") f.write("\nSee, i have added one more line :).") f.close() f = open("textfile.txt", "r") for line in f: print(line)
輸出
There are tons to reason to 'fall in love with PYTHON' See, i have added one more line :).
關閉檔案
完成檔案操作後,必須使用f.close()命令結束操作。這樣,我們就完全關閉了檔案,終止了所有正在使用的資源,並釋放了它們以供系統在其他地方使用。
示例
f = open("textfile.txt", "r") f.close() f.readlines()
輸出
關閉檔案後,任何嘗試使用檔案物件的嘗試都會引發錯誤。
Traceback (most recent call last): File "<pyshell#95>", line 1, in <module> f.readlines() ValueError: I/O operation on closed file.
使用"with"語句
with語句可以與檔案物件一起使用。使用這兩個(with語句和檔案物件),我們在程式中獲得了更簡潔的語法和異常處理。
另一個優點是,一旦我們完成檔案操作,任何開啟的檔案都會自動關閉。
語法
with open(“filename”) as file:
示例
在此示例中,檔案在with塊結束時自動關閉,因此無需顯式呼叫close()方法。
with open("example.txt", "w") as file: file.write("This is an example using the with statement.") print ("File closed successfully!!")
輸出
File closed successfully!!