dsaiztc
6/30/2015 - 2:19 PM

Python CSV management. https://docs.python.org/2/library/csv.html

import csv

filename = 'file.csv'

# Read CSV
with open(filename, 'rb') as csvfile:
  csvreader = csv.reader() # Common values -> delimiter=',' quotechar='"'
  for row in reader:
    pass
  
  csvreader.fieldnames # Initialized with the first record from the file

# Read CSV with different characteristics
with open(filename, 'rb') as csvfile:
  csvreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
  for row in reader:
    pass
  
# Write to CVS
with open('some.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(someiterable)
    writer.writerow(somerow)
    
# Read CSV into Dictionary
with open('names.csv') as csvfile:
  reader = csv.DictReader(csvfile)
  for row in reader:
    print(row['first_name'], row['last_name'])

# Write CSV from Dictionary
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})