Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: write to file multiple times without open/close for each write

Tags:

python

file

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?

like image 569
grizwako Avatar asked Mar 18 '10 20:03

grizwako


2 Answers

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").

like image 152
lazy1 Avatar answered Sep 29 '22 08:09

lazy1


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
like image 26
brettkelly Avatar answered Sep 29 '22 10:09

brettkelly