在Python中写入文件时如何保留旧内容?
在本文中,我们将讨论在Python编写文件时保留旧内容的各种方法。
通过以追加模式打开文件,我们可以在使用Python写入时保留旧内容。要以追加模式打开文件,我们可以使用“ a ”或“ a+ ”作为访问模式。这些访问方式的定义如下:
- Append Only ('a'):打开文件进行写入。如果文件不存在,则创建该文件。手柄位于文件的顶部。正在写入的数据将插入在当前数据之后的顶部。
- Append with Read ('a+'):打开文件进行读写。如果文件不存在,则创建该文件。手柄位于文件的顶部。正在写入的数据将插入在当前数据之后的顶部。
方法:
- 我们将首先以追加模式打开文件,即使用“a”或“a+”访问模式打开文件。
- 现在,我们将简单地在文件底部添加内容,从而保留文件的旧内容。
- 然后,我们将关闭程序中打开的文件。
我们将使用以下文本文件来执行所有方法:
以下是上述方法的完整实现:
示例 1:将新内容添加到文件,同时保留旧内容,以“a”作为访问模式。
Python3
# Python program to keep the old content of the file
# when using write.
# Opening the file with append mode
file = open("gfg input file.txt", "a")
# Content to be added
content = "\n\n# This Content is added through the program #"
# Writing the file
file.write(content)
# Closing the opened file
file.close()
Python3
# Python program to keep the old content of the file
# when using write.
# Opening the file with append mode
file = open("gfg input file.txt", "a+")
# reach at first
file.seek(0)
# Reading the file
content = file.read()
# view file content
print(content)
# Content to be added
content = "\n\n# This Content is added through the program #"
# Writing the file
file.write(content)
# Closing the opened file
file.close()
输出:
示例 2:将新内容添加到文件中,同时保留以“a+”作为访问模式的旧内容。
蟒蛇3
# Python program to keep the old content of the file
# when using write.
# Opening the file with append mode
file = open("gfg input file.txt", "a+")
# reach at first
file.seek(0)
# Reading the file
content = file.read()
# view file content
print(content)
# Content to be added
content = "\n\n# This Content is added through the program #"
# Writing the file
file.write(content)
# Closing the opened file
file.close()
输出:
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.