Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
所以我写了一个简单的脚本,将一些行写入文件:
f = open('file.txt','w') while(operator): f.write("string") f.close()
问题是,当脚本运行时文件仍然是空的,只有当脚本完成并关闭文件时,内容才可见。发生了什么,我怎样才能使它在脚本运行时立即显示脚本写入文件的内容?
我正在运行 BackTrack 5 来运行脚本。
您需要使用f.flush(). 它将缓冲区中的当前内容写入文件,
f.flush()
In [17]: f.flush.__doc__ Out[17]: 'flush() -> None. Flush the internal I/O buffer.'
使用该with语句处理文件,因为它会自动为您关闭文件:
with
with open("file.txt","w") as f: while(operator): f.write("string") f.flush()