0

我正在尝试使用相同的数据创建两个文件。一个文件用于更新实时 Web 数据,另一个文件用作日志。需要经常追加和更新一个文件。我可以很好地创建日志,但正在努力处理如何处理第二个文件的数据。

我尝试对日志文件使用“with open”语句。当我尝试将其读入实时网页时,它会向我显示之前记录的数据,并且仅在文件关闭时更新数据。

#!/usr/bin/env python2.7

import os
import RPi.GPIO as GPIO
import time
import subprocess

#Solar Panel Script 1.0

#Set pin for Pump Relay Signal (PR = pin 29)

#Set up Pump Relay BCM5 (pin 29) as output pin in off position
GPIO.setmode(GPIO.BCM)
GPIO.setup (5, GPIO.OUT, initial=0)
GPIO.setwarnings(False)

#Load Hot Water Tank (HWT), Solar Panel (SP), and Outside Temp (OT) with OWFS

#Create CSV File for temperature data
from time import sleep, strftime, time
with open("/var/www/html/data.csv", "a") as log:
        while True:
                with open ("/mnt/1wire/28.C14777910F02/temperature", "r") as myfile:
                        HWT=myfile.read().replace('\n', '')
                        myfile.close()
                with open ("/mnt/1wire/28.390877910402/temperature", "r") as myfile2:
                        SP=myfile2.read().replace('\n', '')
                        myfile.close()
                log.write("{0},{1},{2}\n".format(strftime("%Y-%m-%d %H:%M:%S"), str(HWT), str(SP)))

#Solar Hot Water Heater Module
#Turns on PR only if SP is 10F hotter than HWT.  Checks OT for frezing temps, if less than 33, PR is off.
                print ('hot water: ' + HWT)
                print ('solar panel: '+ SP)
                flt_HWT = float(HWT)
                flt_SP = float(SP)

                if flt_HWT > 170:
                        GPIO.output(5, GPIO.LOW) #Pump Relay Off
                if flt_SP > (flt_HWT + 10):
                        GPIO.output(5, GPIO.HIGH) #Pump Relay On
                state = GPIO.input(5)
                print state
                sleep(20) #10 Minutes = 600

我希望日志文件允许我在它打开时从中收集数据。

4

1 回答 1

0
log.write("{0},{1},{2}\n".format(strftime("%Y-%m-%d %H:%M:%S"), str(HWT), str(SP)))

这是你写日志的地方。您可以在此处简单地包含另一个 with open() 语句

with open("secondfile.log") as secfile:
    log.write("{0},{1},{2}\n".format(strftime("%Y-%m-%d %H:%M:%S"), str(HWT), str(SP))) ##original log file can be here
    secfile.write("{0},{1},{2}\n".format(strftime("%Y-%m-%d %H:%M:%S"), str(HWT), str(SP))) ##and here you are wrighting the second file.

但是,如果您正在编写多个文件,最好将它们粘贴到它们自己的功能中。

def write_file(text, filename):
    try:
        with open(filename) as file:
            file.write(text)
        return True
    except:
        return False ##include any other exception stuff here

现在你可以使用

success = write_file("log text", "filename.log")
if success:
     success = write_file("log2 text", "filename2.log")
if success:
    print("Yey both files have been written to")
else:
    print("Awww, there was an error writing to the file")
于 2019-02-12T15:27:33.213 回答