擅长:python、mysql、java
<p>您可以使用“w+”或“r+”模式进行读写。当你以文本模式打开一个文件时,默认情况下它是完全缓冲的。要查看实时更新,您必须<code>flush</code>每次写入或以行缓冲模式打开文件(<code>buffering=1</code>)。<br/>
此外,您不能使用<code>tail -f</code>,因为文件没有附加。要观看实时更新,您必须反复调用<code>cat</code>,所以<code>watch cat fruits.txt</code>也可以。在</p>
<p>我在这里模拟了你的情景。在</p>
<pre><code>from time import sleep
fruits = dict(apple=1, banana=2, orange=3)
with open('fruits.txt', 'w+', buffering=1) as f:
for _ in range(20):
for fruit, count in fruits.items():
f.write('{}: {}\n'.format(fruit, count))
f.seek(0)
for line in f:
line = line.strip().split(':')
line[1] = int(line[1]) + 1
fruits.update((line,))
f.seek(0)
sleep(1)
</code></pre>