将一些数据放入 .csv 文件的脚本创建了文件,但它是空白的

Script that put some data in a .csv file created the file , but it's blank

基本上,我创建的代码必须做 3 件事: 1 - 从 DS18B20 传感器读取温度 2 - 在 .csv 文件中写入温度和验证时间 3 - 使用 .csv 文件中的数据绘制图形 这是代码:

import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        return temp_c
while True:
    print(read_temp())  
    time.sleep(1)
with open("/home/pi/cpu_temp.csv", "a") as log:
    while True:
        temp = temp_c
        log.write("{0},{1}\n".format(strftime("%d-%m-%Y %H:%M"),str(temp)))
        sleep(5)

import matplotlib.pyplot as plt
plt.ion()
x = []
y = []
y.append(temp)
x.append(time())
plt.clf()
plt.scatter(x,y)
plt.plot(x,y)
plt.draw

谁能告诉我这是什么问题?我会自己修复它而不问这个问题,但我实际上不知道出了什么问题,代码运行正常,没有错误。

您的写入文件代码块:

with open("/home/pi/cpu_temp.csv", "a") as log:
    while True:
        temp = temp_c
        log.write("{0},{1}\n".format(strftime("%d-%m-%Y %H:%M"),str(temp)))
        sleep(5)

永远不会执行,因为在它之前执行了一个无限循环:

while True:
    print(read_temp())  
    time.sleep(1)