Python 如何在文本文件中写入多行
Python具有用于创建、读取和写入文件的内置函数,以及其他文件操作。普通文本文件和二进制文件是Python可以处理的两种基本文件类型。本文将介绍如何在Python中将内容写入文本文件。
使用Python在文本文件中写入多行的步骤
以下是使用Python在文本文件中写入多行的方法:
- 必须使用open()方法以写入模式打开文件,并给函数提供文件路径。
- 下一步是写入文件。可以使用几个内置方法,如write()和writelines()来实现。
- 在写入过程结束后,必须使用close()方法关闭文本文件。
注意 :下面提到的所有示例都遵循上述步骤。
open()函数
如果可以打开文件,open()函数会执行此操作并返回相应的文件对象。
open()函数有多个参数。让我们来看看写入文本文件所需的参数。在选择的模式下打开文件后,它返回一个文件对象。
语法
file = open('filepath','mode')
在此处,
- filepath(文件路径) − 它代表文件的路径。
- mode(模式) − 它包含了许多可选参数。它是一个字符串,指示文件的打开模式。
使用writelines()函数
此函数同时将多个字符串行写入文本文件。可以将一个可迭代对象(如列表、集合、元组等)发送到writelines()方法。
语法
file.writelines(list)
这是一个示例,用Python写入文件多行的方法:
示例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
极客笔记