Reputation: 1563
How can i open file in python and write to it multiple times?
I am using speech recognition, and i want one file to change its contents based on what i say. Other application needs to be able to read this file. Is there way to do this, or i need to open/close for each write?
Upvotes: 6
Views: 19808
Reputation: 13910
You can just keep the file object around and write to it whenever you want. You might need to flush
it after each write to make things visible to the outside world.
If you do the writes from a different process, just open the file in append mode ("a").
Upvotes: 11
Reputation: 28245
f = open('myfile.txt','w')
f.write('Hi')
f.write('Hi again!')
f.write('Is this thing on?')
# do this as long as you need to
f.seek(0,0) # return to the beginning of the file if you need to
f.close() # close the file handle
Upvotes: 7