Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
644 views
in Technique[技术] by (71.8m points)

how to add lines to existing file using python

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')

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...