2016-09-23 81 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)