In my work, I had to take data continuously → write it to a CSV file and take a log. I tried to summarize it as a memorandum.
OS:Raspbian Buster 10 Software used: Code-OSS (headmelted) 1.44.0
Create an empty CSV file in the same hierarchy as the program and write the log to it. Add the date first, like "AD / month / day hour: minute: second, (data 1), (data 2) ..." List the data you want to record behind, separated by commas.
Python
csvWrite.py
import csv
import datetime
n = 0
try:
with open('logger.csv', 'a') as f:
#Write log 10 times
while n < 10:
#Date Time
now = datetime.datetime.now()
nowTime = '{0:%Y/%m/%d %H:%M:%S}'.format(now)
#Data group
data1 = 'data1'
data2 = 'data2'
data3 = 'data3'
writeStr = nowTime + ',' + data1 + ',' + data2 + ',' +data3
writeStr = writeStr.split(',')
#Confirmation of the written character string
#Example:'2020/03/06 15:00:00','data1','data2','data3'
print('writeStr = %s' % writeStr)
writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
writer.writerow(writeStr)
n += 1
except FileNotFoundError as e:
print(e)
except csv.Error as e:
print(e)
csvWrite.c
#include <stdio.h>
#include <time.h>
FILE *fp;
char *fname = "logger.csv";
struct tm tm;
int main(void)
{
struct tm tm;
time_t t;
//Data group
char data1[] = "data1";
char data2[] = "data2";
char data3[] = "data3";
//Open the file (if it doesn't exist, it will be created automatically)
fp = fopen(fname, "a");
if(fp == NULL){
printf("file can't open¥n");
return -1;
}
//Write log 10 times
for(int n = 0; n < 10; n++){
//Date Time
t = time(NULL);
localtime_r(&t, &tm);
fprintf(fp, "\"%04d/%02d/%02d %02d:%02d:%02d\",",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
fprintf(fp, "\"%s\",\"%s\",\"%s\"\n", data1, data2, data3);
//Confirmation of the written character string
//Example:"2020/03/06 15:00:00","data1","data2","data3"
printf("writeStr = \"%04d/%02d/%02d %02d:%02d:%02d\",\"%s\",\"%s\",\"%s\"\n",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec, data1, data2, data3);
}
fclose(fp);
return 0;
}
When I am developing IoT, I leave a log on the server, but when I can not connect to the Internet The feeling of despair when the log disappears during that time is amazing, so I would like to create a CSV file on the SD card and save it diligently in this way.
Recommended Posts