Python:多次写入文件而不为每次写入打开/关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2473202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: write to file multiple times without open/close for each write
提问by grizwako
How can i open file in python and write to it multiple times?
如何在python中打开文件并多次写入?
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?
我正在使用语音识别,并且我想要一个文件根据我所说的内容更改其内容。其他应用程序需要能够读取此文件。有没有办法做到这一点,或者我需要为每次写入打开/关闭?
回答by lazy1
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.
您可以保留文件对象并随时写入。您可能需要flush
在每次写入后使用它才能使外部世界可见。
If you do the writes from a different process, just open the file in append mode ("a").
如果您从不同的进程进行写入,只需以追加模式(“a”)打开文件。
回答by inkedmn
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