• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Python and CSV

Contents

  • Reading CSV files
  • Writing CSV files
  • See also

Python has a very nice module called csv which makes working with CSV very easy. This mini article is only a reminder for me so that I can easily find how to use it when I forget once again how it is used exactly.

Reading CSV files

try:
    from future.builtins import open
except:
    pass

import csv

with open('eggs.csv', 'rt', newline='') as csvfile:
    csvreader = csv.reader(csvfile, delimiter=';', quotechar='"')
    next(csvreader, None)  # skip the headers
    for row in csvreader:
        print(', '.join(row))

Writing CSV files

try:
    from future.builtins import open
except:
    pass

import csv

with open('eggs.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile,
                           delimiter=';',
                           quotechar='"',
                           quoting=csv.QUOTE_MINIMAL)
    csvwriter.writerow(['Spam'] * 5 + ['Baked Beans'])  # Write header
    for row in container:
        csvwriter.writerow(row)  # Write data

See also

  • Open files in 'rt' and 'wt' modes
  • Python+CSV on StackOverflow

Published

Feb 8, 2015
by Martin Thoma

Category

Code

Tags

  • CSV 2
  • Python 90

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor