Python 写文件追加:按行追加

Python 写文件追加:按行追加

Python 写文件追加:按行追加

1. 简介

在Python中,我们可以使用open()函数来打开一个文件,并使用文件对象的write()方法来写入内容。如果要在已有文件的末尾追加内容,我们可以使用文件对象的a模式或a+模式来打开文件。本文将详细介绍如何使用Python追加写文件的方法,并提供一些示例代码帮助读者理解。

2. 追加写文件的方法

Python提供了几种不同的方法来追加写文件。下面是其中的两种常用方法。

2.1 使用write()方法追加写文件

使用文件对象的write()方法可以实现追加写文件的功能。当文件以a模式或a+模式打开时,write()方法将在文件的末尾追加写入内容。

首先,让我们创建一个sample.txt的文本文件,并在其中写入一些内容:

with open('sample.txt', 'w') as file:
    file.write('This is line 1.\n')
    file.write('This is line 2.\n')
Python

现在,我们可以使用追加模式重新打开文件,然后使用write()方法向文件中追加内容:

with open('sample.txt', 'a') as file:
    file.write('This is line 3.\n')
    file.write('This is line 4.\n')
Python

以上代码将在已有文件的末尾追加两行文字。如果我们再次打开sample.txt文件,将可以看到如下内容:

This is line 1.
This is line 2.
This is line 3.
This is line 4.

可以看到,新写入的两行文字成功地追加在了原文本的末尾。

2.2 使用print()函数追加写文件

除了使用文件对象的write()方法,我们还可以使用Python的print()函数来实现追加写文件功能。通过指定文件对象和file参数,我们可以将print()函数的输出直接追加到指定文件中。

以下是使用print()函数追加写文件的示例代码:

with open('sample.txt', 'a') as file:
    print('This is line 5.', file=file)
    print('This is line 6.', file=file)
Python

运行以上代码后,我们的sample.txt文件将变为:

This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
This is line 6.

如你所见,print()函数的输出也被成功地追加在了文件的末尾。

3. 示例代码运行结果

下面我们将使用一个完整的示例代码来演示追加写文件的方法,并展示代码的运行结果。

# 创建文件并写入内容
with open('sample.txt', 'w') as file:
    file.write('This is line 1.\n')
    file.write('This is line 2.\n')

# 追加写文件
with open('sample.txt', 'a') as file:
    file.write('This is line 3.\n')
    file.write('This is line 4.\n')

# 使用print()函数追加写文件
with open('sample.txt', 'a') as file:
    print('This is line 5.', file=file)
    print('This is line 6.', file=file)
Python

运行以上代码后,我们的sample.txt文件内容为:

This is line 1.
This is line 2.
This is line 3.
This is line 4.
This is line 5.
This is line 6.

以上就是Python中追加写文件的详细介绍和示例代码。希望本文能帮助读者理解如何使用write()方法和print()函数来实现追加写文件的功能。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册