简体   繁体   English

如何在保留旧行的同时在文本文件中写新行

[英]How can I write on new lines in a text file while preserving old ones

When I open a text file and write in it and at the end of the program close it, the lines stay in the text file. 当我打开一个文本文件并写入其中,并在程序结束时将其关闭时,这些行将保留在文本文件中。 When i reopen that program, rather than writing on a new set of lines, it overwrites what is already there. 当我重新打开该程序时,而不是在新的一行上编写,它会覆盖已经存在的内容。 I want to keep both pieces of text, it is for data logging. 我想保留这两段文字,这是用于数据记录的。 Any ideas on how to fix this. 有想法该怎么解决这个吗。

You should use the a mode, like this: 您应该使用a模式,如下所示:

with open("file","a") as f:
    f.write("Something") 

This will append to the file instead of overwriting it. 这将追加到文件中而不是覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何写入新文本文件而不是旧文件 - How to write into a new text file and not to an old one 如何将文本的特定行写入新文件? - How to write specific lines of a text to a new file? 使用 write() 时如何附加到文件的新行? - How can I append to the new line of a file while using write()? 如何编写第一个文本文件中不存在的第二行文本中的行? - How can I write the lines from the first text file that are not present in the second text file? 除了特定的文本块,如何将行写入新文件? - How to write lines to a new file except for a specific block of text? 如何使用变量将文本行写入文件? - How do I write text lines to file with variables to a file? 我如何在多个文本文件中搜索模式并写入新的多个文本文件 - How I can search pattern in multiple text file and write in to new multiple text file also 如何在文件中搜索所有以某种格式开头的数字开头的文本行并将其移动到新行 - How can I search a file for all text lines prefaced with numbers in a certain format and move them to a new line 在附加文件时,如何使用Python在文本文件中的旧信息下方添加新信息 - While appending a file how to add new information underneath old information in text file using Python 如何写成多行的txt文件? - How can i write to a txt file with multiple lines?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM