Python txt 追加写入
在Python中,我们可以使用open()
函数来打开一个文件,并使用'a'
模式来进行追加写入操作。追加写入的操作会将新的内容添加到文件的末尾,而不会覆盖掉原有的内容。本文将详细介绍如何在Python中进行txt文件的追加写入操作。
打开文件并追加写入内容
首先,我们使用open()
函数打开一个txt文件,并指定模式为'a'
,示例代码如下:
file_path = 'example.txt'
with open(file_path, 'a') as file:
file.write('Hello, world!\n')
在上面的代码中,我们打开了一个名为example.txt
的文件,并使用'a'
模式进行打开。然后,我们通过write()
方法向文件中写入了一行内容Hello, world!
,并在末尾加上了换行符\n
。
追加写入多行内容
如果我们想追加写入多行内容,可以通过循环的方式一行一行地写入,示例代码如下:
file_path = 'example.txt'
lines = ['First line\n', 'Second line\n', 'Third line\n']
with open(file_path, 'a') as file:
for line in lines:
file.write(line)
在上面的代码中,我们定义了一个字符串列表lines
,其中包含了三行内容。然后,我们通过循环逐行将内容写入到example.txt
文件中。
追加写入变量内容
除了直接写入字符串内容,我们还可以将变量的值写入到文件中,示例代码如下:
file_path = 'example.txt'
name = 'Alice'
age = 30
with open(file_path, 'a') as file:
file.write(f'My name is {name}, and I am {age} years old.\n')
在上面的代码中,我们定义了两个变量name
和age
,然后使用f-string的格式化字符串将它们的值写入到文件中。
运行结果
当我们运行以上示例代码后,会将对应的内容追加写入到example.txt
文件中。如果example.txt
文件原本为空,运行后文件内容如下:
Hello, world!
First line
Second line
Third line
My name is Alice, and I am 30 years old.
通过以上示例,我们详细介绍了在Python中进行txt文件的追加写入操作。