Python 中讀取和寫入文字檔案
與其他語言一樣,Python 提供了一些內建函式用於讀取、寫入或訪問檔案。Python 主要處理兩種型別的檔案:普通文字檔案和二進位制檔案。
對於文字檔案,每行都以特殊的字元 '\n' 結尾(稱為 EOL 或行尾)。對於二進位制檔案,沒有行尾字元。它在將內容轉換為位元流後儲存資料。
在本節中,我們將討論文字檔案。
檔案訪問模式
序號 | 模式及描述 |
---|---|
1 | r 只讀模式。它開啟文字檔案進行讀取。如果檔案不存在,則會引發 I/O 錯誤。 |
2 | r+ 讀寫模式。如果檔案不存在,則會引發 I/O 錯誤。 |
3 | w 只寫模式。如果檔案不存在,則會先建立一個檔案,然後開始寫入;如果檔案存在,則會刪除該檔案的內容,然後從開頭開始寫入。 |
4 | w+ 寫讀模式。如果檔案不存在,則可以建立檔案;如果檔案存在,則資料將被覆蓋。 |
5 | a 追加模式。它將資料寫入檔案的末尾。 |
6 | a+ 追加和讀取模式。它可以追加資料以及讀取資料。 |
現在讓我們看看如何使用 writelines() 和 write() 方法寫入檔案。
示例程式碼
#Create an empty file and write some lines line1 = 'This is first line. \n' lines = ['This is another line to store into file.\n', 'The Third Line for the file.\n', 'Another line... !@#$%^&*()_+.\n', 'End Line'] #open the file as write mode my_file = open('file_read_write.txt', 'w') my_file.write(line1) my_file.writelines(lines) #Write multiple lines my_file.close() print('Writing Complete')
輸出
Writing Complete
寫入行之後,我們將一些行追加到檔案中。
示例程式碼
#program to append some lines line1 = '\n\nThis is a new line. This line will be appended. \n' #open the file as append mode my_file = open('file_read_write.txt', 'a') my_file.write(line1) my_file.close() print('Appending Done')
輸出
Appending Done
最後,我們將看到如何使用 read() 和 readline() 方法讀取檔案內容。我們可以提供一個整數 'n' 來獲取前 'n' 個字元。
示例程式碼
#program to read from file #open the file as read mode my_file = open('file_read_write.txt', 'r') print('Show the full content:') print(my_file.read()) #Show first two lines my_file.seek(0) print('First two lines:') print(my_file.readline(), end = '') print(my_file.readline(), end = '') #Show upto 25 characters my_file.seek(0) print('\n\nFirst 25 characters:') print(my_file.read(25), end = '') my_file.close()
輸出
Show the full content: This is first line. This is another line to store into file. The Third Line for the file. Another line... !@#$%^&*()_+. End Line This is a new line. This line will be appended. First two lines: This is first line. This is another line to store into file. First 25 characters: This is first line. This
廣告