Masthead

Reading Files with the CSV Library

 

1. Introduction

There is a relatively new library for reading CSV files. This library will deal with issues with quotes and commas inside of strings and is recommended for reading CSVs until you get a CSV that is in a non-standard form.

2. Split

When we read data from a text file or a web service, the information we want is usually buried within other text. When you created your text files you took values and put them into a tab-delimited or comma-separate file. If you want to get to the data again, you need to parse the text to find what you are interested in.

There are a wide variety of formats for text and a large number of functions for parsing them. However, one of the most common, and easiest to work with, are the text files we just created. The "split()" function will break up a string into individual elements based on a "delimiter" like a tab or comma character. Let's try this first in Python with a string you define:

import csv
TheFile=open("C:/Temp3/all_hour.csv","r") # open the file for reading (thus the "r")
TheCSVReader=csv.reader(TheFile) # create an object to read the file as a CSV file
NumRows=0
for TheRow in TheCSVReader: # Loop on each line in the file 
   if (NumRows>0): # skip the header line
	print(TheRow[0]) # print the first value in the row
	NumRows+=1
   
TheFile.close()

Additional Resources

Python Documentation: CSV Reading and Writing

 

© Copyright 2018 HSU - All rights reserved.