Home > Net >  How to append to a file an already existing output?
How to append to a file an already existing output?

Time:11-08

So I am using a raspberry pi and sense hat. I'm trying to write code to find the temperature, humidity, and pressure every minute, then save it to a file. I've already written code that will find temp, pressure, and humidity every minute. ->

from sense_hat import SenseHat
from time import time, sleep
while True:
  sleep(1 - time() % 1) # 
  sense = SenseHat()
  # Take readings from all three sensors
  t = pressure = sense.get_pressure()
  print(pressure)
  p = temp = sense.get_temperature()
  print(temp)
  h = humidity = sense.get_humidity()
  print(humidity)

  # Round the values to one decimal place
  t = round(t, 1)
  p = round(p, 1)
  h = round(h, 1)

  # Create the message
  # str() converts the value to a string so it can be concatenated
  message = "Temperature: "   str(t)   " Pressure: "   str(p)   " Humidity: "   str(h)

  # Display the scrolling message
  sense.show_message(message, scroll_speed=0.05)

from time import time, sleep
while True:
    sleep(60 - time() % 60)

Now I need to save the output information to a file. I know that I can append whatever I want to say by using ->

f = open("sensedata.txt", "a")
f.write("temp, pressure, humidity")
f.close()

#open and read the file after the appending:
f = open("sensedata.text", "r")
print(f.read())

But I need to be able to append data that I've already found aka temp pressure and humidity. I have tried appending " t \n, h \n, p \n," because I've already defined that t = temp p = pressure and h = humidity but it literally came up on the file as t \n, h \n, p \n. I don' know what I should do.

CodePudding user response:

use it:

f = open("sensedata.txt", "a")
f.write(f" {t} \n, {h} \n, {p} \n,")
f.close()

to get more info about work with string in python click here and here

string concating in python:

1-simple:

a="welcome"
b="stackoverflow"
print(a      " to "       b) 

output is: welcome to stackoverflow

note: in this method a and b must be str

2-f string

print(f'{a} to {b}')

3-format

print(('{} to {}').format(a, b))

CodePudding user response:

Separating out the reading and the writing into different function is a good idea.

To append to the file you want to open it with mode a and to create it for the first time you open it with mode w.

It is often helpful with sensor reading to have the results as a CSV file for later processing.

Here is an example of what that might look like:

import csv
from datetime import datetime
from pathlib import Path

from sense_hat import SenseHat
from time import sleep

CSV_LOG = Path('/tmp/sensor_readings.csv')
sense = SenseHat()


def read_sensor():
    return {
        "Time": datetime.utcnow().isoformat(),
        "Pressure": round(sense.get_pressure(), 1),
        "Temperature": round(sense.get_temperature(), 1),
        "Humidity": round(sense.get_humidity(), 1),
    }


def show_reading(sensor_reading):
    print(f'{sensor_reading=}')


def write_reading(sensor_reading):
    first_write = not CSV_LOG.exists()
    open_mode = 'w' if first_write else 'a'
    with CSV_LOG.open(open_mode) as csvfile:
        fieldnames = ["Time", "Temperature", "Pressure", "Humidity"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if first_write:
            writer.writeheader()
        writer.writerow(sensor_reading)


def main():
    while True:
        sleep(10)
        sensor_values = read_sensor()
        show_reading(sensor_values)
        write_reading(sensor_values)


if __name__ == '__main__':
    main()

My test printing out the following:

sensor_reading={'Time': '2021-11-07T18:07:29.445745', 'Pressure': 63, 'Temperature': 33, 'Humidity': 45}
sensor_reading={'Time': '2021-11-07T18:07:39.455906', 'Pressure': 72, 'Temperature': 25, 'Humidity': 37}
sensor_reading={'Time': '2021-11-07T18:07:49.458768', 'Pressure': 45, 'Temperature': 24, 'Humidity': 71}

And wrote the following to /tmp/sensor_readings.csv:

Time,Temperature,Pressure,Humidity
2021-11-07T18:07:29.445745,33,63,45
2021-11-07T18:07:39.455906,25,72,37
2021-11-07T18:07:49.458768,24,45,71
  • Related