gpt4 book ai didi

Python while循环不写入所有数据只是最后一次阅读

转载 作者:行者123 更新时间:2023-11-28 16:57:12 24 4
gpt4 key购买 nike

我正在设置一个温度/湿度传感器并编写了一个 while 循环来将数据记录在一个单独的文件中。我试图将写入更改为追加,但是我的文件仍然只包含最后一个数据点。

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

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

下面的while循环

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!')

运行程序时,控制台显示所有数据,但我尝试写入的 example.txt 文件仅显示最后一个数据点。我希望得到如下列表。

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%

最佳答案

您可以尝试读取文件并将其添加到字符串中,而不是将新数据连接到文件字符串中,然后将其写入文件中

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

关于Python while循环不写入所有数据只是最后一次阅读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57245987/

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