python_and_csvs

One of the primary tasks I personally use Python for is data collection and manipulation. In this post I’ll walk you through some basic CSV file work.

Reading from a CSV File

Take the CSV file below, it’s a collection of collected ADC points with the acquisition number preceding it. We’re going to take this CSV file, read it in Python, and display it in the command prompt.

The Python script below is an example of how this can be done. Walking through the file, we first import the csv definitions. This provides us access to all of the functions in pycsv. Next, we open the file and assign it to the csvfile object. Then we read the file with the specified delimiter. Finally, we cycle through the file and print the parsed contents one at a time.

The results of running the script in the Enhanced Console can be seen in the capture below.

csv_read_example

Writing to a CSV File

Writing to a CSV file is similar. The primary deltas are they you create a write object and write the needed values to a row. One caveat to the casting done on line 11, is that the data read from the CSV file are all text, so if you want to do math to it then you need to cast it as an integer, do the math, then cast that result back to a string to write it to the file.

This results in the output file below.

Leave a Reply

Your email address will not be published. Required fields are marked *