如何使用python向现有文件添加行 [英] how to add lines to existing file using python
问题描述
我已经使用python创建了一个txt文件,其中包含几行文本,这些文本将由一个简单的程序读取.但是,我在重新打开文件以及在程序的后续部分中在文件中写入其他行时遇到了一些麻烦. (这些行将从稍后获得的用户输入中写入.)
I already created a txt file using python with a few lines of text that will be read by a simple program. However, I am having some trouble reopening the file and writing additional lines in the file in a later part of the program. (The lines will be written from user input obtained later on.)
with open('file.txt', 'w') as file:
file.write('input')
这是假设'file.txt'之前已打开并写入.但是在第二次打开时,使用我当前拥有的代码,我必须擦除之前编写的所有内容并重写新行.有没有办法防止这种情况发生(并可能减少再次打开文件的过多代码)?
This is assuming that 'file.txt' has been opened before and written in. In opening this a second time however, with the code that I currently have, I have to erase everything that was written before and rewrite the new line. Is there a way to prevent this from happening (and possibly cut down on the excessive code of opening the file again)?
推荐答案
如果要附加到文件,请使用'a'
打开它.如果要在文件中查找以找到应插入行的位置,请使用'r+'
. (文档)
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
这篇关于如何使用python向现有文件添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!