drizzyyy
drizzyyy

Reputation: 29

Creating csv file with python code

I'm not too sure how to make a csv file with my current python code. Don't get me wrong, I don't want someone to do all this for me, I just want help getting started on.

My Code

I want the csv file to record the Name, Gender, DOB, Measurement, Weight, Height and their . Just a reminder that I don't want people to do the whole code for me, just want to get started.

Upvotes: 1

Views: 137

Answers (2)

Subhransu Majhi
Subhransu Majhi

Reputation: 11

Exactly as Diyi Wang said, here is a snippet of that document :

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

From: https://docs.python.org/2/library/csv.html#csv.writer

Upvotes: 0

Boa
Boa

Reputation: 2677

If the problem is actually generating the CSV, one variant is the CSV module.

Create a list of column headers. For example:

fieldnames = ['Name', 'Gender', 'DOB', 'Measurement', 'Weight', 'Height']

Get your data into a list of dicts, with each key corresponding to a header field. For example, something like:

data = [{'Name': 'James', 'Gender': 'M', 'DOB': [some DOB], ...},
        {'Name': 'Dave', 'Gender': 'M', 'DOB': [some DOB], ...},
        ...]

Write your header and data:

with open('data.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    for cur_dict in data:
        writer.writerow(cur_dict)

Upvotes: 4

Related Questions