You are on page 1of 11

READING FROM CSV FILES

WHAT ARE CSV FILES?

We have looked at writing to and reading from text files.


Sometimes we want to store data in ordered columns (like a
spreadsheet).
This means we can search for a data in a particular column for
example, using the file below we could check a username and
password are correct before allow someone access to our program.
To do

In Excel create the file below


Click on save as and use the arrow
in the save as type box to save as
a csv
Save it as usernames.csv
What do you think the output of this code will be?

row[0] row[1] row[2] row[3]


Take a closer look
This demonstrates how to open a CSV file and read each
row, as well as reference specific data on each row.

Import the csv module


create a csv reader object called readCSV
that points to a file called username.csv

Loop through each row in the file


1
2
3

1 print the whole row

2 print the contents of the first column of the current row

3 print the contents of each column of the current row


Using the same csv. What would the output for this program be?
Using the same csv. What would the output for this program be?
Create this program.

Extension use selection to ignore the


header row (so the headings are not
written to the list)
Answer to extension
INDEPENDENT ACTIVITY

1) Create a program to ask the user for their username and


password.
2) Check the file to see if they have entered a valid username and
password (must be in the same row)
3) If it is valid print a message which welcomes them to your world
4) Include their name (also from the file) in your message
5) If their username is found but not a matching password, display
a suitable message asking if they would like to reset their
password

You might also like