Python - 寫入檔案



寫入檔案涉及以特定模式開啟檔案,向其中寫入資料,然後關閉檔案以確保所有資料都被儲存並且資源被釋放。Python 提供了內建函式 `open()` 來處理檔案操作以及各種寫入資料的方法。

開啟檔案以進行寫入

開啟檔案以進行寫入是執行 Python 寫入操作的第一步。`open()` 函式用於以不同的模式開啟檔案,每種模式都適合於特定用例。

`open()` 函式

Python 中的 `open()` 函式用於開啟檔案。它至少需要一個引數,即檔名,並且可以接受一個可選的第二個引數,該引數指定應以何種模式開啟檔案。

寫入檔案的模式

以下是您可以用來開啟檔案以進行寫入的主要模式:

  • w(寫入模式)− 開啟檔案以進行寫入。如果檔案存在,則在寫入之前會截斷(清空)檔案。如果檔案不存在,則建立一個新檔案。

  • a(追加模式)− 資料寫入檔案的末尾。如果檔案不存在,則建立一個新檔案。

  • x(獨佔建立模式)− 開啟檔案以進行獨佔建立。如果檔案已存在,則操作失敗。

  • b(二進位制模式)− 與其他模式一起使用時,以二進位制模式開啟檔案。

  • +(更新模式)− 開啟檔案以進行更新(讀取和寫入)。

示例:以寫入模式開啟檔案

此模式用於當您希望將資料寫入檔案時,每次開啟檔案時都從頭開始:

file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
print ("File opened successfully!!")

以下是獲得的輸出:

File opened successfully!!

示例:以追加模式開啟檔案

此模式用於當您希望將資料新增到檔案的末尾而不更改其現有內容時:

file = open("example.txt", "a")
file.write("Appending this line.\n")
file.close()
print ("File opened successfully!!")

這將產生以下結果:

File opened successfully!!

使用 write() 方法寫入檔案

write() 方法用於向檔案寫入單個字串。這使其適用於各種基於文字的檔案操作。

write() 方法接受一個引數:要寫入檔案的字串。它將字串的精確內容寫入檔案,不會新增任何其他字元,例如換行符。

示例

在下面的示例中,我們以寫入模式開啟檔案“example.txt”。然後,我們使用 write() 方法將字串寫入檔案:

# Open a file in write mode
with open("example.txt", "w") as file:
   file.write("Hello, World!\n")
   file.write("This is a new line.\n")
print ("File opened successfully!!")

以上程式碼的輸出如下:

File opened successfully!!

使用 writelines() 方法寫入檔案

writelines() 方法用於將字串列表寫入檔案。列表中的每個字串都按順序寫入檔案,不會自動新增任何換行符。

示例

在這個例子中,我們建立了一個字串列表 lines,每個字串以換行符結尾。然後,我們以寫入模式開啟檔案“example.txt”,並使用 writelines() 方法一次性將列表中的所有字串寫入檔案:

# List of lines to write to the file
lines = ["First line\n", "Second line\n", "Third line\n"]

# Open a file in write mode
with open("example.txt", "w") as file:
    file.writelines(lines)

print ("File opened successfully!!")

獲得的輸出如下所示:

File opened successfully!!

寫入新檔案

在 Python 中寫入新檔案包括建立新檔案(或覆蓋現有檔案)並將所需內容寫入其中。在這裡,我們將解釋寫入新檔案所涉及的步驟:

  • 開啟檔案 - 使用 open() 函式以寫入模式(“w”或二進位制檔案的“wb”)建立或開啟檔案。

  • 寫入資料 - 使用 write() 或 writelines() 方法將資料寫入檔案。

  • 關閉檔案 - 確保在寫入後正確關閉檔案,通常使用“with”語句進行自動處理。

示例

在下面的示例中,我們建立一個“foo.txt”檔案,並將給定的內容寫入該檔案,最後關閉該檔案:

# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opened file
fo.close()

如果您使用任何文字編輯器應用程式(例如記事本)開啟此檔案,它將包含以下內容:

Python is a great language.
Yeah its great!!

以二進位制模式寫入新檔案

預設情況下,對檔案物件的讀/寫操作是在文字字串資料上執行的。如果我們需要處理不同型別的檔案,例如媒體檔案 (mp3)、可執行檔案 (exe) 或圖片 (jpg),則必須透過在讀/寫模式前新增“b”字首以二進位制模式開啟檔案。

將二進位制資料寫入檔案

要將二進位制資料寫入檔案,請以二進位制寫入模式 ('wb') 開啟檔案。以下示例演示了這一點:

# Open a file in binary write mode
with open('test.bin', 'wb') as f:
   # Binary data
   data = b"Hello World"  
   f.write(data)

將文字字串轉換為位元組

可以使用 encode() 函式將文字字串轉換為位元組。當您需要將文字資料作為二進位制資料寫入時,這很有用:

# Open a file in binary write mode
with open('test.bin', 'wb') as f:
   # Convert text string to bytes
   data = "Hello World".encode('utf-8')  
   f.write(data)

寫入現有檔案

當以寫入模式 ('w') 開啟現有檔案時,其先前的內容將被擦除。使用寫入許可權開啟檔案將其視為新檔案。要將資料新增到現有檔案而不擦除其內容,應以追加模式 ('a') 開啟檔案。

示例

以下示例演示如何以追加模式開啟檔案並向其中新增新文字:

# Open a file in append mode
fo = open("foo.txt", "a")
text = "TutorialsPoint has a fabulous Python tutorial"
fo.write(text)

# Close opened file
fo.close()

如果您使用任何文字編輯器應用程式(例如記事本)開啟此檔案,它將包含以下內容:

Python is a great language.
Yeah its great!!
TutorialsPoint has a fabulous Python tutorial

以讀寫模式寫入檔案

當使用 'w' 或 'a' 開啟檔案進行寫入時,無法在檔案的任何較早位元組位置執行寫入操作。但是,'w+' 模式允許讀寫操作而無需關閉檔案。seek() 函式用於將讀/寫指標移動到檔案中的任何所需位元組位置。

使用 seek() 方法

seek() 方法用於設定檔案內讀/寫指標的位置。seek() 方法的語法如下:

fileObject.seek(offset[, whence])

其中:

  • offset - 這是檔案內讀/寫指標的位置。

  • whence - 這是可選的,預設為 0,這意味著絕對檔案定位;其他值為 1,表示相對於當前位置查詢;2 表示相對於檔案結尾查詢。

示例

以下程式演示如何以讀寫模式 ('w+') 開啟檔案,寫入一些資料,查詢特定位置,然後覆蓋檔案內容的一部分:

# Open a file in read-write mode
fo = open("foo.txt", "w+")

# Write initial data to the file
fo.write("This is a rat race")

# Move the read/write pointer to the 10th byte
fo.seek(10, 0)

# Read 3 bytes from the current position
data = fo.read(3)

# Move the read/write pointer back to the 10th byte
fo.seek(10, 0)

# Overwrite the existing content with new text
fo.write('cat')

# Close the file
fo.close()

如果我們以讀取模式開啟檔案(或在 'w+' 模式下跳轉到起始位置)並讀取內容,它將顯示以下內容:

This is a cat race
廣告