-
Notifications
You must be signed in to change notification settings - Fork 4
/
write_csv_data.py
75 lines (64 loc) · 2.61 KB
/
write_csv_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#! /usr/bin/python3
# -*- coding: utf-8 -*-
from find_usb import find_dev
from csv import DictWriter, DictReader # write csv data file
import os
import rw_ini as rw
def write_data(data, data_file):
"""Write data in the file (usb or if not available in SD card).
Args:
data (dict): The dict containing the data for each parameter (result dict from function get_data()).
"""
path = find_dev('/media/pi/', data_file)
fieldnames = [
'date',
'time',
'v_up', # V
'v_int', # V
'v_down', # V
'bar_up', # bar
'bar_int', # bar
'bar_down', # bar
'mmH2O_up',
'mmH2O_int',
'mmH2O_down',
'ana_turb', # analog number
'turb', # grams of soil/cm3 of water
'flow',
'liters',
'water_temp',
'air_temp',
'air_hum',
'air_pres',
]
#Put csv extention if not present
if data_file[-4:] != '.csv':
csv_file= data_file + '.csv'
else:
csv_file = data_file
if path == '':
# If there is no storage device, write on disk (RPi sd card) in /srv/EROSTESTS
# don't forget to do 1st: sudo mkdir /srv/EROSTESTS
# sudo chmod - R 777 / srv / EROSTESTS
path = os.path.join('/srv/EROSTESTS', csv_file) #create first the /srv/EROSTESTS/
file_exists = os.path.isfile(path) # sets to TRUE if file exists otherwise FALSE
#os.chmod(path, 0o777)
rw.write_ini_path(path)
with open(path, 'a', newline='') as f: # if the file exists data will be added below after a blank line
writer = DictWriter(f, fieldnames)
if not file_exists:
writer.writeheader() # file doesn't exist yet, write a header
writer.writerow(data) #writes the data in a new blank line
else:
# If storage USB device available
# Create the full path to the file on the device
path = os.path.join(path, csv_file)
file_exists = os.path.isfile(path)
rw.write_ini_path(path)
#os.chmod(path, 0o777)
with open(path, 'a', newline='') as f:# if the file exists data will be added below after a black line
writer = DictWriter(f, fieldnames)
if not file_exists:
writer.writeheader()
writer.writerow(data)