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.

Download a file from the USGS Earthquake Data Center or use this one.

2. Reading CSV Files

The code below uses a "for" loop to read the data in the CSV. "For" loops in Python are not as flexible but work well with data that is in a list and the CSV reader provides access to the rows in a CSV file as a list.

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.