这个Python脚本定义了一个名为new_counter()
的函数,它读取系统时间并将其与存储在文件中的时间进行比较。然后根据比较结果更新存储在另一个文件中的计数器值。如果系统时间与存储的时间匹配,则计数器值增加1。如果系统时间与存储的时间不匹配,则计数器重置为0。
当您运行脚本时,它会打印当前的计数器值。
请注意,文件路径是相对于脚本的位置的,根据您的具体文件结构,可能需要调整这些路径。
def new_counter():
# 获取系统时间
import time
cur = time.time()
local_time = time.localtime(cur)
current = time.strftime("%Y/%m/%d", local_time)
print('系统当前时间:',current)
# 文件路径
import os.path
path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# print(path+r'/case_com/system_time.txt')
file_path_time = path+r'/comm/system_time.txt'
file_path_sum = path+r'/comm/counter_sum.txt'
try:
with open(file_path_time, 'r') as file:
data_time = file.read()
print('读取文件时间:', data_time)
if str(current) == str(data_time):
print('系统时间和保存文件时间相等')
with open(file_path_sum, 'r') as file:
coun_data = file.read()
print('读取当前文件保存计数:', coun_data)
with open(file_path_sum, 'w') as file:
coun_data = int(coun_data) + 1
file.write(str(coun_data))
print('计数 +1:', coun_data)
with open(file_path_sum, 'r') as file:
coun_data = file.read()
print('读取文件最新计数值:', coun_data)
return coun_data
elif str(current) != str(data_time):
print('不相等')
with open(file_path_sum, 'w') as file:
file.write('0')
print('写入0')
with open(file_path_time, 'w') as file:
file.write(current)
except FileNotFoundError:
print('文件不存在')
with open(file_path_time, 'w') as file:
file.write('2024/01/09')
with open(file_path_sum, 'w') as file:
file.write('0')
print('写入0')
if __name__ == '__main__':
print(new_counter())