Skip to content

Instantly share code, notes, and snippets.

@christophergregory
Last active August 29, 2015 14:05
Show Gist options
  • Save christophergregory/5f88b3c95fb7f7caf11b to your computer and use it in GitHub Desktop.
Save christophergregory/5f88b3c95fb7f7caf11b to your computer and use it in GitHub Desktop.
Python 101 Assignment 3 Solution 2
import csv
# Open all required files with at once
with open('numbers.txt', 'r') as numbersfile, \
open('birthdays.txt', 'r') as birthdayfile, \
open('output.txt', 'w') as output:
# Read in each line as a dictionary
# https://docs.python.org/2/library/csv.html#csv.DictReader
numReader = csv.DictReader(numbersfile, fieldnames=['Name','Number'])
bdayReader = csv.DictReader(birthdayfile, fieldnames=['Name','Birthday'])
# Create writer object
# https://docs.python.org/2/library/csv.html#csv.DictWriter
dictWriter = csv.DictWriter(output, ['Name','Birthday','Number'])
dictWriter.writeheader()
# skip first line in each reader
# https://docs.python.org/2/library/functions.html#next
next(numReader)
next(bdayReader)
# Create a list of dictionaries
# Can you figure out why I am choosing to build a list
# instead of just looping through the iterators
# that numReader/bdayReader outputs above?
numRows = [row for row in numReader]
bdayRows = [row for row in bdayReader]
# Nested loop to find matches and write to new file
for num in numRows:
for bday in bdayRows:
if num['Name'] == bday['Name']:
row = {
'Name' : num['Name'],
'Number' : num['Number'],
'Birthday' : bday['Birthday']
}
dictWriter.writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment