首先要做的是
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()等
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)