如何使用 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-08-18

24K+ 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.