Continuously Update A File

浪尽此生 提交于 2021-02-19 07:16:07

问题


Ultimately I need to make info from the Spotify API available to an app that will display "current song" info, including cue time.

So will need to be continuously polling the API, as well as updating the data source the App is polling.

I'm still trying to wrap my head around thinking of data in terms of streams as opposed to files.

So I came up with this little experiment for how a file can be continuously updated:

import itertools
for i in itertools.count(start=0, step=1):
    f = open('info.txt', 'w')
    f.write(str(i))
    f.close()

It even sort of works. I can open or cat info.txt and intermittently see:

  • nothing
  • a numeral from an increasing series

Why nothing sometimes?

Additionally confusing, inside the interactive python terminal a stream of slowly incrementing low numerals is output, beginning at 4:

4
4
4
4
etc...
5
5
5
5
etc...

Is using f.write an advisable approach to continuously updating a row of data that can be consumed as a file?


回答1:


Try the following:

import os
import shutil
import itertools
for i in itertools.count(start=0, step=1):
    f = open('tmp', 'w')
    f.write(str(i))
    f.close()
    shutil.move('tmp', 'info.txt')

Unlike the open-write-close sequence of operations, the file move is an atomic operation which avoids catching the info.txt file in an "unstable" state i.e. after the open and before the write operation.



来源:https://stackoverflow.com/questions/62707420/continuously-update-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!