GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing pythonprogramming.net — Python Programming Tutorials Reading CSV files in PythonThis Python 3 tutorial covers how to read CSV data in from a file and then use it in Python. For this, we use the csv module. CSV literally stands for comma separated variable, where the comma is what is known as a "delimiter." While you can also just simply use Python's split() function, to separate lines and data within each line, the CSV module can also be used to make things easy. Here is the sample code that matches the video: Example CSV file data: 1/2/2014,5,8,red 1/3/2014,5,2,green 1/4/2014,9,1,blue Next, let's cover the reading of CSV files into memory: import csv
with open('example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for row in readCSV:
print(row)
print(row[0])
print(row[0],row[1],row[2],)
Above, we've shown how to open a CSV file and read each row, as well as reference specific data on each row. Next, we will show how to pull out specific data from the spreadsheet and save it to a list variable: import csv
with open('example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
dates = []
colors = []
for row in readCSV:
color = row[3]
date = row[0]
dates.append(date)
colors.append(color)
print(dates)
print(colors)
Once we have this data, what can we do with it? Maybe we are curious about what color something was on a specific date. import csv
with open('example.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
dates = []
colors = []
for row in readCSV:
color = row[3]
date = row[0]
dates.append(date)
colors.append(color)
print(dates)
print(colors)
# now, remember our lists?
whatColor = input('What color do you wish to know the date of?:')
coldex = colors.index(whatColor)
theDate = dates[coldex]
print('The date of',whatColor,'is:',theDate)
Simple enough! If we enter something that doesn't exist, we get an ugly error. There exists 1 challenge(s) for this tutorial. for access to these, video downloads, and no ads.
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |