简体   繁体   中英

Python while loop not writing all data just last reading

I am setting up a temperature/humidity sensor and wrote a while loop to record the data in a separate file. I've tried to change the write to append, however my file still only contained the last data point either way.

file = open('/home/pi/example.txt','a')

file = open('/home/pi/example.txt','w') 

while loop below

import Adafruit_DHT
from time import sleep
from datetime import datetime

# Sensor should be set to Adafruit_DHT.DHT11,
sensor = Adafruit_DHT.DHT11

# Example using a Raspberry Pi with DHT sensor connected to GPIO4.
pin = 4

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 4 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)


while True:
        if humidity is not None and temperature is not None:
                print (datetime.now()),('Temp={0:0.1f}*F  Humidity={1:0.1f}%'.format(temperat$
                temphumid = (datetime.now()),('Temp={0:0.1f}*F  Humidity={1:0.1f}%'.format(te$
                x = str(temphumid)
                file = open('/home/pi/example.txt','a')         
                file.write(x) 
                file.close()            
                sleep(4)
        else:
                print('Failed to get reading. Try again!')

when running the program the console shows all data however the example.txt file I am trying to write to is only showing the last data point. I expected a list like below.

2019-07-28 17:28:00.400339 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:04.405064 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:08.409786 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:12.414289 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:16.419099 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:20.423903 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:24.428758 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:28.433569 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:32.438289 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:36.443027 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:40.447963 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:44.452716 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:48.457465 Temp=120.2*F  Humidity=19.0%
2019-07-28 17:28:52.462201 Temp=120.2*F  Humidity=19.0%

You could try to read the file and add it into string than concatenate the new data to the file string write that to the file

file = open('file.txt','r+')
file_string = file.read()
new_string = '{}more data\n'.format(file_string)
file.write(new_string)
file.close()

The following code resolves the original issue, that each statement wasn't written to the file. Additionally, it resolves the unstated issue that temperature and humidity are never updated after the first method call.

from time import sleep
from datetime import datetime
from pathlib import Path
import Adafruit_DHT

sensor_data = Path('sensor.txt')
if not sensor_data.exists():
    with sensor_data.open('w') as f:
        f.write('time,temp(F),humidity(%)\n')
with sensor_data.open('a') as f:
    try:
        while True:
            humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
            if humidity and temperature:
                time_now = datetime.now()
                temp_hum = (f'{time_now} Temp={temperature:0.2f}\u00b0F Humidity={humidity:0.2f}%')
                print(temp_hum)
                f.write(f'{time_now},{temperature},{humidity}\n')
                sleep(4)
            else:
                print('Failed to get reading. Try again!')
                sleep(4)
    except KeyboardInterrupt:
        pass

Code breakdown:

  1. if not sensor_data.exists : if the file doesn't exist, create it and write a header
  2. with open : no close statement required
  3. f'string {variable}' : modern f-strings (python 3.6)
  4. write data to the file in a way that makes it easy to import and analyse
  5. try: except will allow you to properly exit the while loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM