9.12.1 Python Standard Library Module csv

  • csv module provides functions for working with CSV files

Writing to a CSV File

  • csv module’s documentation recommends opening CSV files with the additional keyword argument newline='' to ensure that newlines are processed properly
In [1]:
import csv
In [2]:
with open('accounts.csv', mode='w', newline='') as accounts:
    writer = csv.writer(accounts)
    writer.writerow([100, 'Jones', 24.98])
    writer.writerow([200, 'Doe', 345.67])
    writer.writerow([300, 'White', 0.00])
    writer.writerow([400, 'Stone', -42.16])
    writer.writerow([500, 'Rich', 224.62])
  • .csv file extension indicates a CSV-format file
  • writer function returns an object that writes CSV data to the specified file object
  • writer’s writerow method receives an iterable to store in the file
  • By default, writerow delimits values with commas, but you can specify custom delimiters
In [3]:
!cat accounts.csv
100,Jones,24.98
200,Doe,345.67
300,White,0.0
400,Stone,-42.16
500,Rich,224.62
  • writerow calls above can be replaced with one writerows call that outputs a comma-separated list of iterables representing the records
  • If you write data that contains commas in a given string, writerow encloses that string in double quotes to indicate a single value

Reading from a CSV File

  • Read records from the file accounts.csv and display the contents of each record
In [4]:
with open('accounts.csv', 'r', newline='') as accounts:
    print(f'{"Account":<10}{"Name":<10}{"Balance":>10}')
    reader = csv.reader(accounts)
    for record in reader:  
        account, name, balance = record
        print(f'{account:<10}{name:<10}{balance:>10}')
Account   Name         Balance
100       Jones          24.98
200       Doe           345.67
300       White            0.0
400       Stone         -42.16
500       Rich          224.62
  • csv module’s reader function returns an object that reads CSV-format data from the specified file object
  • Can iterate through the reader object one record of comma-delimited values at a time

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.