Create and read csv


Spreadsheets often export CSV (comma seperated values) files, because they are easy to read and write. A csv file is simply consists of values, commas and newlines.  While the file is called ‘comma seperate value’ file, you can use another seperator such as the pipe character.

Create a spreadsheet file (CSV) in Python
Let us create a file in CSV format with Python. We will use the comma character as seperator or delimter.

import csv
 
with open('persons.csv', 'wb') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    filewriter.writerow(['Name', 'Profession'])
    filewriter.writerow(['Derek', 'Software Developer'])
    filewriter.writerow(['Steve', 'Software Developer'])
    filewriter.writerow(['Paul', 'Manager'])

Running this code will give us this fil persons.csv with this content:

Name,Profession
Derek,Software Developer
Steve,Software Developer
Paul,Manager

You can import the persons.csv file in your favorite office program.

python csv
Spreadsheet file created in Python

 

Read a spreadsheet file (csv) 
If you created a csv file, we can read files row by row with the code below:

import csv
 
# open file
with open('persons.csv', 'rb') as f:
    reader = csv.reader(f)
 
    # read file row by row
    for row in reader:
        print row

This will simply show every row as a list:

['Name', 'Profession']
['Derek', 'Software Developer']
['Steve', 'Software Developer']
['Paul', 'Manager']

Perhaps you want to store that into Python lists. We get the data from the csv file and then store it into Python lists. We skip the header with an if statement because it does not belong in the lists. Full code:

import csv
 
# create list holders for our data.
names = []
jobs = []
 
# open file
with open('persons.csv', 'rb') as f:
    reader = csv.reader(f)
 
    # read file row by row
    rowNr = 0
    for row in reader:
        # Skip the header row.
        if rowNr >= 1:
            names.append(row[0])
            jobs.append(row[1])
 
        # Increase the row number
        rowNr = rowNr + 1
 
# Print data 
print names
print jobs

Result:

['Derek', 'Steve', 'Paul']
['Software Developer', 'Software Developer', 'Manager']

Most spreadsheet or office programs can export csv files, so we recommend you to create any type of csv file and play around with it 🙂

Next tutorial: Zip archives


31 thoughts on “Create and read csv

  1. Kathryn - July 14, 2016

    Hi Frank,

    Is there a reason the lists are “initialized” twice?

    names = []
    jobs = []

    1. Frank - July 15, 2016

      Hi Kathryn,

      Thanks for noticing! It should have been “initialized” only once.

  2. Victor - December 12, 2015

    Hi Frank. I have some problem for the first program. After running the code. I have a file persons.csv but it looks like this .
    Name,Profession

    Derek,Software Developer

    Steve,Software Developer

    Paul,Manager

    How can I cancel those empty lines between them? Thanks.

    1. Frank - December 13, 2015

      Try to add a comma after your print command. Alternative is print(row.replace(“\n”,””))

  3. Jenna - November 28, 2015

    Great resource. However, when I try to read a cvs file I keep getting
    Could not find a part of the path ‘C:\Program Files\Rhinoceros 5 (64-bit)\System\artist_song_list\artists-songs-albums-tags.csv’.
    Traceback:
    line 4, in script
    even though I just put the file in Rhino’s System. Thoughts?

    1. Frank - November 29, 2015

      Thanks Jenna! Try to put the file between quotes or using double slashes: ‘C:\\Program Files\\Rhinoceros 5 (64-bit)\\System\\artist_song_list\\artists-songs-albums-tags.csv’. A single slash in Python is used as escape characters, such as \n for newline.

  4. Mat - October 14, 2015

    Frank
    Thanks for this. New to Python and haven’t programmed for many years. I want to read a multi-row.csv file (float), and I’ve copied your code into Phycharm.

    import csv

    # open file
    with open(‘gisp2short.csv’, ‘rb’) as f:
    reader = csv.reader(f)

    # read file row by row
    for row in reader:
    print row

    I’m getting an error message “SyntaxError: Missing parentheses in call to ‘print'”.
    What am I doing wrong?
    TIA
    Mat

    1. Frank - October 17, 2015

      Hi Mat! Change the last line to print(row). Python3 requires brackets to be around the print command.

  5. Stewart - October 12, 2015

    Something is wrong with the ‘read and write files’ page. It doesn’t complete loading and I can’t scroll the pages. Then I get an error that the page is not responding and to recover it – which doesn’t work either. Please fix.

    1. Frank - October 17, 2015

      Hi stewart, which file are you trying to read? There is no scrolling, the data is simply in a variable. To scoll you need a textbox widget

      1. Scot - December 8, 2015

        Hi Frank,
        He means the https://pythonspot.com/read-write-files/ page has an error on it.

        Great site, btw.

        1. Frank - December 8, 2015

          Thanks Scot! I’ll look at this asap