Skip to content

Instantly share code, notes, and snippets.

@shinichi-takayanagi
Created October 26, 2021 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinichi-takayanagi/77814f79e5ccfedbad078c6dc85df419 to your computer and use it in GitHub Desktop.
Save shinichi-takayanagi/77814f79e5ccfedbad078c6dc85df419 to your computer and use it in GitHub Desktop.
Snippet for CSV read/write
import csv
# write
with open('names.csv', 'w', newline='') as file:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(file, 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'})
# read
with open("names.csv") as file:
reader = csv.DictReader(file)
for row in reader:
print(row['first_name'], row['last_name'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment