gpt4 book ai didi

python - 读取输入数据到csv文件

转载 作者:行者123 更新时间:2023-12-02 01:51:53 24 4
gpt4 key购买 nike

我正在做一个通过传感器测量温度的 BeagleBone 项目。我想将数据保存到 CSV 文件中。我是编程和 Python 的新手,我几乎没有迷路。我已经在谷歌上搜索了一段时间,但发现几乎没有什么可以帮助我的。所以我想问问这个。如何每秒将新数据写入 CSV 文件?

import Adafruit_BBIO.ADC as ADC
import time
import csv

sensor_pin = 'P9_40'

ADC.setup()

while True:
reading = ADC.read(sensor_pin)
millivolts = reading * 1800 # 1.8V reference = 1800 mV
temp_c = (millivolts - 500) / 10
temp_f = (temp_c * 9/5) + 32
print('mv=%d C=%d F=%d' % (millivolts, temp_c, temp_f))

time.sleep(1)

# field names
fields = ['Milivolts', 'Celsius']


# data rows of csv file
rows = [ [millivolts,"|", temp_c]]

# name of csv file
filename = "textfile.csv"

# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)

# writing the fields
csvwriter.writerow(fields)

# writing the data rows
csvwriter.writerows(rows)

最佳答案

应用的一个修复是在追加模式下打开文件,这样文件内容就不会在每一步都被覆盖;只需将这一行中的 'w' 更改为 'a':

with open(filename, 'a') as csvfile:

请注意,如果没有任何输出和/或描述您遇到的问题,将很难为您提供更多帮助。

关于python - 读取输入数据到csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70147943/

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