如何使用 Python 在文本文件中写入多行?

programmingpythonserver side programming更新于 2025/3/22 17:16:17

Python 具有用于创建、读取和写入文件以及其他文件操作的内置函数。普通文本文件和二进制文件是 Python 可以处理的两种基本文件类型。在本文中,我们将介绍如何在 Python 中将内容写入文本文件。

使用 Python 在文本文件中写入多行所涉及的步骤

以下是使用 Python 在文本文件中写入多行的方法 -

  • 必须使用 open() 方法打开文件进行写入,并且必须为该函数提供文件路径。
  • 下一步是写入文件。可以使用几种内置方法(例如 write() 和 writelines)来执行此操作()。
  • 写入过程完成后,必须使用 close() 方法关闭文本文件。

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

Open() 函数

如果可以打开文件,open() 函数将执行此操作并返回匹配的文件对象。

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

相关文章


有用资源