如何使用Python在文字檔案中寫入多行?


Python 內建了用於建立、讀取和寫入檔案以及其他檔案操作的函式。Python 可以處理兩種基本的檔案型別:普通文字檔案和二進位制檔案。本文將介紹如何在 Python 中將內容寫入文字檔案。

使用Python在文字檔案中寫入多行的步驟

以下是使用Python在文字檔案中寫入多行的方法:

  • 必須使用open()方法開啟檔案進行寫入,並向函式提供檔案路徑。
  • 下一步是寫入檔案。可以使用多種內建方法來實現這一點,例如write()和writelines()。
  • 寫入過程完成後,必須使用close()方法關閉文字檔案。

注意 - 下面提到的所有示例都遵循上述步驟。

Open() 函式

如果可以開啟檔案,open()函式會開啟它並返回相應的 file 物件。

open()函式有很多引數。讓我們來看看寫入文字檔案所需的那些引數。它在選擇的模式下開啟檔案後返回一個檔案物件。

語法

file = open('filepath','mode')

其中:

  • filepath - 表示檔案的路徑。
  • mode - 包含許多可選引數。它是一個字串,指示檔案的開啟模式。

使用 writelines() 函式

此函式一次性將多行字串寫入文字檔案。可以向 writelines() 方法傳遞一個可迭代物件,例如列表、集合、元組等。

語法

file.writelines(list)

其中list 是將要新增的文字或位元組的集合。它可以是字串集合、元組、列表等。

示例 - 1

以下是如何使用 Python 在檔案中寫入多行的示例:

with open('file.txt', 'a') as file: l1 = "Welcome to TutorialsPoint\n" l2 = "Write multiple lines \n" l3 = "Done successfully\n" l4 = "Thank You!" file.writelines([l1, l2, l3, l4])

輸出

輸出結果是一個名為“file”的文字檔案,其中包含以下寫入的行:

Welcome to TutorialsPoint
Write multiple lines
Done successfully
Thank You!

示例 - 2

以下是用 Python 寫入檔案多行的另一種示例:

with open("file.txt", "w") as file: lines = ["Welcome to TutorialsPoint\n", "Write multiple lines \n", "Done successfully\n" ] file.writelines(lines) file.close()

輸出

輸出結果是一個名為“file”的文字檔案,其中包含以下寫入的行:

Welcome to TutorialsPoint
Write multiple lines
Done successfully

示例 - 3:使用 while 迴圈

以下是如何使用 while 迴圈在檔案中寫入多行的示例:

# declare function count() def write(): # open a text file in read mode and assign a file object with the name 'file' file=open("file.txt",'w') while True: # write in the file l=input("Welcome to TutorialsPoint:") # writing lines in a text file file.write(l) next_line=input("The next line is printed successfully:") if next_line=='N': break file.close() write()

輸出

以下是上述程式碼的輸出:

Welcome to TutorialsPoint:
The next line is printed successfully:

使用 writelines() 函式

如果要向現有文字檔案新增更多行,則必須首先以追加模式開啟它,然後使用 writelines() 函式,如下所示。

示例

以下是如何在文字檔案中追加多行的示例:

with open("file.txt", "a") as f: lines = ["Adding lines\n", "writing into it \n", "written successfully\n" ] f.writelines(lines) f.close()

輸出

我們在已有的檔案中追加了多行:

Welcome to TutorialsPoint
Write multiple lines
Done successfully
Adding lines
writing into it
written successfully

更新於:2022年8月18日

24K+ 次檢視

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.