python3 将读取到的字符串写入文件,不覆盖之前写入的内容
时间: 2024-10-15 09:17:09 浏览: 42
在Python 3中,如果你想将读取到的字符串追加到已存在的文件末尾,而不是替换原有内容,可以使用内置的open()
函数以追加模式("a"
)打开文件。这里是一个例子:
with open('filename.txt', 'a') as file:
content = "这是需要追加的字符串"
file.write(content)
在这个例子中,'a'
表示append
,即打开文件后默认会在文件末尾添加新的内容。如果文件不存在,它会被自动创建。
如果你只是想要一次性读取并追加所有数据,你可以先读取旧内容再写入:
# 如果文件存在
try:
with open('filename.txt', 'r') as read_file:
old_content = read_file.read()
except FileNotFoundError:
old_content = "" # 或者处理文件不存在的情况
with open('filename.txt', 'a') as write_file:
new_content = "这是需要追加的字符串"
write_file.write(new_content)
# 合并旧内容和新内容
total_content = old_content + new_content
这样会首先尝试读取文件内容,然后在末尾添加新的字符串。
相关推荐


















