This is my first attempt at writing Python script - it's probably a bit ambitious, but there again, whatever doesn't kill you makes you stronger... ;-)
I'm trying to write a script for a datalogger, which will import data from a laboratory flow meter at regular user-defined intervals via a serial port connection, then save it as a CSV file which can then be opened in Excel for analysis.
The imported data is in the form of an 18-byte long comma delimited ASCII character string which I've helpfully called "data".
e.g.: 12.345,100.23,22.5
Each comma delimited value will represent a column, and each string of data will represent a seperate row in the Excel spreadsheet.
So far (with some help from the Bytes community!) I've managed to import a string of data, print it to screen, and save it as a csv file using the code listed below. My "Print to screen" and "Save to file" routines are embedded in a "While" loop, which loops round repeatedly until the required (user defined) number of data strings have been collected.
I can see all the results printed to the screen, but using my "Save to file" routine in this way means that the data file is constantly being over-written, and the only data that ends up saved to the file is the last string to be collected.
I was wondering if there is a Python command along the lines of "append to file", that I could use which would allow me to write successive strings of data to the .csv file without over-writing the previous entries.
I guess the alternative is to use Python to keep adding each new data string to the end of the previous ones,
seperated by a suitable "new row" character, to make one long "master string" for subsequent import into Excel. However, the "master string" may end up rather long - I'm planning to collect data at a rate of 1 new 18 byte string every 10 seconds for a couple of hours! Also, if the data connection or power supply was interrupted at any stage during data acquisition, all the data collected might be lost if this method was used...
I'm sure this must be a fairly routine problem, but I'm not sure of the best solution, and would be very grateful for your help & advice.
Many thanks in anticipation
Dave
Expand|Select|Wrap|Line Numbers
- #Write recieved data to file
- data=data + "\n"
- print "Writing data to file 'c:/test/a.csv'"
- fob=open('c:/test/a.csv','w')
- fob.write(data)
- fob.close()