Python:每次写入时多次写入文件而不打开/关闭

gri*_*ako 5 python file

如何在python中打开文件并多次写入?

我正在使用语音识别,我希望根据我的说法改变其内容.其他应用程序需要能够读取此文件.有没有办法做到这一点,或者我需要为每次写入打开/关闭?

laz*_*zy1 7

您可以随时保留文件对象并随时写入.flush每次写入后您可能需要它以使外部世界可见.

如果您从其他进程执行写入操作,只需以附加模式("a")打开该文件.


ink*_*dmn 6

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
Run Code Online (Sandbox Code Playgroud)

  • 永远不要依赖于显式调用 `close`。**始终** 使用上下文管理器(`with open('myfile.txt', 'w') as f`)。 (2认同)
  • 永远不要说,“永远不要说永远”。 (2认同)