【发布时间】:2021-10-17 04:30:04
【问题描述】:
当我使用函数 write 时,然后在 txt 文件中获取所有新文本。我需要在文件中添加附加文本而不删除旧文本。这可能吗?
问候, 马吕斯
【问题讨论】:
标签: python function file text write
当我使用函数 write 时,然后在 txt 文件中获取所有新文本。我需要在文件中添加附加文本而不删除旧文本。这可能吗?
问候, 马吕斯
【问题讨论】:
标签: python function file text write
尝试在a模式下阅读:
with open("filename.txt", "a") as f:
f.write("text goes here...")
【讨论】:
为此,您必须使用 append mode== "a" 在不删除旧文本的情况下不删除附加文本
f =open("file.txt","a")
f.write("Writing in text file old text not deleted ")
f.close()
【讨论】:
f = open('filename.txt', 'a')
f.writelines('一些文字')
This wouldn't truncate your text file and will start appending text to your file. 'w' would truncate the old file and start the file as fresh.
【讨论】:
参考这个有用的python文档-https://docs.python.org/3/library/functions.html#open,你会发现文件IO的所有不同模式。
"r" 用于读取,"w" 用于写入,"a" 用于附加,"r+" 用于读取和写入等等......
【讨论】: