gpt4 book ai didi

linux - 解析行python

转载 作者:太空宇宙 更新时间:2023-11-04 12:08:32 25 4
gpt4 key购买 nike

   self.filename = d.get('filename', '/var/www/html/data/reading.txt')
syslog.syslog(syslog.LOG_INFO, "pond: using %s" % self.filename)
self.bind(weewx.NEW_ARCHIVE_RECORD, self.read_file)

def read_file(self, event):
try:
with open(self.filename) as f:
#value = f.read()
f.seek(-8, os.SEEK_END)
line = f.readlines()[-1]
value = line.split(',')
syslog.syslog(syslog.LOG_DEBUG, "pond: found value of %s" % value)
event.record['ccwatt'] = float(value[0])
event.record['cctemp'] = float(value[1])
except Exception, e:
syslog.syslog(syslog.LOG_ERR, "pond: cannot read value: %s" % e)

上面的 python 会读取 txt 文件的最后一行,并添加一条新的存档记录,例如:

123,54

当只有一个值可用于记录时,如何更改它以添加存档记录。显然 split(',') 不会对一个值起作用

123 

最佳答案

一个快速的条件语句应该可以解决这个问题:

            if "," in line:
value = line.split(',')
else:
value = line

添加到您的代码中:

    self.filename = d.get('filename', '/var/www/html/data/reading.txt')
syslog.syslog(syslog.LOG_INFO, "pond: using %s" % self.filename)
self.bind(weewx.NEW_ARCHIVE_RECORD, self.read_file)

def read_file(self, event):
try:
with open(self.filename) as f:
#value = f.read()
f.seek(-8, os.SEEK_END)
line = f.readlines()[-1]
if "," in line:
value = line.split(',')
else:
value = line
syslog.syslog(syslog.LOG_DEBUG, "pond: found value of %s" % value)
event.record['ccwatt'] = float(value[0])
event.record['cctemp'] = float(value[1])
except Exception, e:
syslog.syslog(syslog.LOG_ERR, "pond: cannot read value: %s" % e)

关于linux - 解析行python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com