. csv files

Evening, I'm wanting to display readings from my compass on a webpage using Apache2 I've read an article https://www.phidgets.com/education/learn/projects/pi-website-2/ where they store the sensor readings in a .csv file that is then accesed by the webpage. I've attached the python script I'm using to display my readings in terminal using print. Could you please show me how to create a .csv fie using these readings as I'm not sure where in the script I should place this part copied from the article.

while (True):
    #Write data to file in CSV format
    with open ('/var/www/html/data.csv','a') as datafile:
        datafile.write(str(temperatureSensor.getTemperature()) + "\n")

and how to modify it for my compass readings.

Thanks
John

Attachments: 
piborg's picture

In a .csv file entries are split into columns by commas and rows by new lines. CSV stands for comma separated values :)

By convention each value will have its own column in the file and each separate reading for them has its own line. Sometimes a heading line is also added at the top. For example:

Time (s),Temperature (°C)
0,20.1
5,22.4
10,22.3
15,22.6
20,22.5

As CSV files are human-readable you can open the output file (/var/www/html/data.csv) using a text editor to check the values are what you expect them to be.

If you just want the single heading reading from your script, then all you need to do is change out the value in the str call so it writes this out instead:

with open ('/var/www/html/data.csv','a') as datafile:
	datafile.write(str(heading) + "\n")

If you want multiple values then you can chain them together with a comma like this:

with open ('/var/www/html/data.csv','a') as datafile:
	datafile.write(str(temperatureSensor.getTemperature()) + "," + str(heading) + "\n")

You want to insert the new code after all of your values have been calculated, but before any long delays. In your case this is just above the time.sleep line at the bottom of your while loop.

On a side-note, your print and time.sleep lines are indented so that they are part of the else block above. I think you intended them to be further to the left so they are only inside the while loop.

Subscribe to Comments for ". csv  files"