Issue
for a project where I want to record sensor data with a Raspberry Pi, I want to save the measurement series for each hour as a new csv file.
How is it possible to automatically create a CSV file with python that has the start and end time of the measurement as name?
I would like to Name the csv files as following: "StartDate + EndDate .csv" But i dont know how to get this working... Here is my approach:
import Adafruit_DHT
import time
import datetime
import pandas as pd
dht_sensor = Adafruit_DHT.DHT11
dht_11_pin = 4
data = {'Date': [], 'Temperature': []}
def readDht11Values(data):
humidity, temperature = Adafruit_DHT.read_retry(dht_sensor, dht_11_pin)
if humidity is not None and temperature is not None:
date = datetime.datetime.now().strftime('%m-%d-%Y_%H.%M.%S')
#print(date)
data["Date"].append(date)
#print('Temperatur={0:0.1f}*C Luftfeuchtigkeit={1:0.1f}%'.format(temperature, humidity))
data["Temperature"].append(temperature)
else:
print('DHT11')
return data
def save_file(data):
df = pd.DataFrame(data)
start = df["Date"][0]
end = df["Date"][len(df)]
name = str(start)+str(end)
filename = str(name)+".csv"
df.to_csv(filename, index=False)
for i in range(0,3):
i = i+1
data = readDht11Values(data)
time.sleep(2)
save_file(data)
Solution
If it is a normal csv
file, one can get away without using pandas at all. For example
def save_file(data):
filename = f"{data['Date'][0]}to{data['Date'][-1]}.csv" # list[-1] gives last element in the list
with open(filename, 'w') as file:
for i in range(0, len(data['Date']):
file.write(f"{data['Date'][i]},{data['Temperature'][i]}\n")
Avoiding pandas can be very useful since it is a kind of an overkill for only writing csv files
Answered By - unityJarvis