持续更新档案 [英] Continuously Update A File

查看:60
本文介绍了持续更新档案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最终,我需要将Spotify API中的信息提供给将显示当前歌曲"的应用,信息,包括提示时间.

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

因此,需要不断轮询API,以及更新应用程序正在轮询的数据源.

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()

它甚至可以工作.我可以打开或cat info.txt并间歇性地看到:

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

  • 没事
  • 一系列递增的数字

为什么有时什么也没有?

Why nothing sometimes?

另外令人困惑的是,在交互式python终端内部,输出从4开始的缓慢递增的低数字流:

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...

是否使用f.write来连续更新可作为文件使用的一行数据的明智方法?

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

推荐答案

尝试以下操作:

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')

与打开-关闭-关闭操作序列不同,文件移动是原子操作,它避免将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.

这篇关于持续更新档案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆