Python: write to file several times without opening / closing for each entry

How can I open a file in python and write to it several times?

I use speech recognition and I want a single file to change its contents based on what I'm saying. Another application should be able to read this file. Is there a way to do this, or do I need to open / close for each entry?

+3
source share
2 answers

You can just save the file object and write it whenever you want. You may need to clear it after each recording to make things visible to the outside world.

If you are recording from another process, simply open the file in add mode ("a").

+5
source
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
+1
source

Source: https://habr.com/ru/post/1737594/


All Articles