Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Writing Python Dictionary to CSV

Just finished the regex course from Kenneth Love this morning and got a chance to put that to use this afternoon, nice timing. Had to parse a 20MB text file looking for email addresses and then write it to a CSV. Just thought I'd share what I ended up doing. Thanks for the skillz!

line = re.compile(r"\s(?P<email>[-\w\d.+]+@[-\w\d.]+)</font", re.X | re.M)


def write_dict_to_csv(csv_file, csv_columns, dict_data):
    try:
        with open(csv_file, 'w') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
            writer.writeheader()
            for key, value in dict_data.items():
                writer.writerow({'email': key, 'pifs_submitted': value})
    except IOError:
        print("I/O error", csv_file)
    return

csv_columns = ['email', 'pifs_submitted']

matches = {}

for match in line.finditer(file_data):
    if match.group('email') not in matches:
        matches[match.group('email')] = 1
    elif match.group('email') in matches:
        matches[match.group('email')] += 1
#

csv_file = 'pif_emails_counted.csv'

write_dict_to_csv(csv_file, csv_columns, matches)

1 Answer