Skip to content

Instantly share code, notes, and snippets.

@dsaiztc
Last active August 29, 2015 14:23
Show Gist options
  • Save dsaiztc/25f04263f21d86258f98 to your computer and use it in GitHub Desktop.
Save dsaiztc/25f04263f21d86258f98 to your computer and use it in GitHub Desktop.
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'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment