2016-09-23 83 views
-2

好吧,我的覆盆子pi连接到我的车库门上的磁性传感器。我有一个python脚本,每秒更新一个网站(initailstate.com)并报告更改,但它在25k请求后花钱,我很快就杀死了大声笑。 我想改为更新文本文件,每次改变门的状态。(打开/关闭)我有一个名为data.txt的文本文件。我有一个网页,它使用java脚本来读取txt文件,并使用ajax来更新和检查文件的变化。这一切都工作,因为我想但我怎么可以得到Python更新文本文件当且仅当该文件的内容是不同的?用python更新文本文件只有当它改变了

我打算在门改变状态后使用python更新文本文件。我可以使用数据库,但我认为一个文本文件将更容易开始。 如果我还没有足够详细,让我知道你对我的需求。

+1

收尾太宽泛。请注意,[所以]不是为您提供您需要的所有代码。 (你可以在Codementor或Airpair上找到帮助)。看看[如何]和什么是[mcve] –

+1

你可以看看'os.stat',看看自上次查找以来文件的修改时间是否发生了变化。 – AChampion

+0

我有一个更新web服务的脚本。我怎样才能更新文本文件。我可以用新的内容覆盖文件 – cfaulk

回答

0

也许你可以尝试这样的事:

f = open("state.txt", "w+") # state.txt contains "True" or "False" 

def get_door_status(): 
    # get_door_status() returns door_status, a bool 
    return door_status 

while True: 
    door_status = str(get_door_status()) 
    file_status = f.read() 
    if file_status != door_status: 
     f.write(door_status) 
0

当是专门为您的小文件时,只需缓存的内容。这对您的存储更快,更健康。

# start of the script 
# load the current value 
import ast 
status, status_file = False, "state.txt" 
with open(status_file) as stat_file: 
    status = ast.literal_eval(next(stat_file())) 

# keep on looping, check against *known value* 
while True: 
    current_status = get_door_status() 
    if current_status != status: # only update on changes 
     status = current_status # update internal variable 
     # open for writing overwrites previous value 
     with open(status_file, 'w') as stat_file: 
      stat_file.write(status)