python中的更新计数器

2024-09-28 23:39:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是一个使用python的程序,它用GPIO计算脉冲数并将它们存储在文本文件中。我想以这样一种方式更新程序:当程序重新启动或更新rapsberry pi时,计数器将继续从之前的最后一次计数开始计数。有人知道怎么做吗?谢谢。在

counter = 0

def my_callback2(channel)

global counter
counter = counter + 1
print counter

file = open("testfile.txt", "w")
file.write(str(counter))

file.close()
with open('testfile.txt', 'r') as f:
    first_line = f.readline()

print "switch press detected"

Tags: 程序txtgpio方式counterpi计数器open
1条回答
网友
1楼 · 发布于 2024-09-28 23:39:15

必须有更简单的方法,但这可以做到:

order_idFile = open('some_file.txt', 'r') # open file for reading
order_id = int(order_idFile.read().strip()) # read file contents, strip it and convert a str to int
order_idFile.close() # close file
order_id += 1 # add 1 to current number
order_idFile = open('some_file.txt', 'w') # open file for writing 
order_idFile.write(str(order_id)) # convert int to str and write to file
order_idFile.close() # close file

注意:
some_file.txt必须有一个有效的数字(0也许?)第一次运行脚本时。在

相关问题 更多 >