tags:

views:

184

answers:

3

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?

+1  A: 
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
inkedmn
Possibly need an `f.seek(0,0)` to rewind back to the beginning.
S.Lott
How about a flush each time? This should not hurt the performance when the input is so slow.
Hamish Grubijan
Never depend on calling `close` explicitly. **Always** use a context manager (`with open('myfile.txt', 'w') as f`).
Mike Graham
Never say never.
Hamish Grubijan
Never say, "never say never."
Seth Johnson
`def never(say): return never(say)`
ΤΖΩΤΖΙΟΥ
+2  A: 

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

lazy1
Thank you, flush() is what i needed.
GrizzLy
+1  A: 

Thank you for suggestions, flush() is what i needed!

GrizzLy