如何使用python将传感器数据输出保存到excel

如何使用python将传感器数据输出保存到excel,第1张

如何使用python将传感器数据输出保存到excel

首先要做的是

import csv
模块,然后使用
with open('file_name.csv', 'w', newline='') ascsvfile:

writer = csv.DictWriter(csvfile, fieldnames=field_names)
field_names

只是您的专栏的关键价值

writer.writerow( {'Date': 'Date', 'Time': 'Time', 'Status': 'Status','Temperature': 'Temperature', 'Humidity': 'Humidity'})
为您的excel文件标题

writer.writerow( {'Date': rightnow.strftime("%d/%m/%Y"), 'Time':rightnow.strftime("%H:%M:%S"), 'Status': status,'Temperature':result.temperature, 'Humidity': result.humidity})

根据中的键值将数据写入csv文件中
field_names

完整代码:

import RPi.GPIO as GPIOimport dht11import timeimport datetimeimport csvimport os# initialize GPIOGPIO.setwarnings(False)GPIO.setmode(GPIO.BCM)GPIO.cleanup()instance = dht11.DHT11(pin=dht11_pin)with open('file_name.csv', 'w', newline='') as csvfile:    field_names = ['Date', 'Time', 'Status', 'Temperature', 'Humidity']    writer = csv.DictWriter(csvfile, fieldnames=field_names)    writer.writerow(        {'Date': 'Date', 'Time': 'Time',         'Status': 'Status', 'Temperature': 'Temperature', 'Humidity': 'Humidity'})    while True:        cnt += 1        if cnt%limit_sec == 0 or cnt == 1: result = instance.read() if result.is_valid():     if previous_temperature != result.temperature or previous_humidity != result.humidity:         previous_temperature = result.temperature         previous_humidity = result.humidity         counter += 1         rightnow = datetime.datetime.now()         if result.humidity>=40:  status = 'Your plant is on the good condition.'  print(str(counter)+". Last valid input: " )  print("Date: " + rightnow.strftime("%d/%m/%Y"))  print("Time: " + rightnow.strftime("%H:%M:%S"))  print("Status: Your plant is on the good condition.")  print("Temperature: %d C" % result.temperature)  print("Humidity: %d %%" % result.humidity)  print("*******************************************")         else:  status = 'Your plant is on the bad condition. Please open the water supply.'  print(str(counter)+". Last valid input: " )  print("Date: " + rightnow.strftime("%d/%m/%Y"))  print("Time: " + rightnow.strftime("%H:%M:%S"))  print("Status: Your plant is on the bad condition. Please open the water supply.")  print("Temperature: %d C" % result.temperature)  print("Humidity: %d %%" % result.humidity)  print("*******************************************")         writer.writerow(  {'Date': rightnow.strftime("%d/%m/%Y"), 'Time': rightnow.strftime("%H:%M:%S"),   'Status': status, 'Temperature':result.temperature, 'Humidity': result.humidity}) else:     print "Invalid result!"     pass        time.sleep(sleep_time)

首先

writer.writerow
是您的标题,
field_names
仅用作将数据填充到垂直列的键

存储您的

status = ''
并将其放入
writer.writerow()



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5629692.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存