0

I am getting "raw" data from a csv file, and putting only what I need for a new csv file that will be used to auto add users to a different system...

I am unsure how to add the correct headers needed for the file.

I've tried looking at other examples of adding headers but have not figured this out yet...

The headers I need to add are as follows:

"ID Card Number","Name","E-Mail","User Level","Position","Status","Covered Under Insurance","Paid Insurance"

(and in that order)

import csv


def studentscsv():
    with open('..\StudentEmails_and_StudentNumbers.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        with open('mydirectory\student_users.csv', mode='w', newline='') as output_file:
            write = csv.writer(output_file, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            for row in csv_reader:
                a = row[0]
                studentnumber = row[1]
                firstname = row[2]
                lastname = row[3]
                grade = row[4]
                studentname = firstname + " " + lastname
                studentemail = firstname + "." + lastname + "@mydomain.org"
                status = "Active"
                position = "Student"
                covered = "Yes"
                paid = "Yes"


                write.writerow([studentnumber, studentname, studentemail, grade, position, status, covered, paid])


def main():
    """
    Controls the program execution
    :param in_file: the name of the input file.
    :return: None
    """


if __name__ == '__main__':
    main()

The file generates fine with the way the code is written. I am just unsure what I need to change to add the headers.

2
  • Possible duplicate of Pythonically add header to a csv file Commented Jan 18, 2019 at 19:13
  • 1
    @MihaiChelaru I respectfully disagree with that assertion as that example is combining data from two different csv files and adding that data and headers to different named csv file. I am simply trying to include headers in the csv file I am generating. Commented Jan 18, 2019 at 19:20

1 Answer 1

5

Using the csv module, as you are, it's pretty straight forward. Define your headers in an array and then create a DictWriter with the fieldnames set to your array. Reference the following code and documentation:

  import csv

  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'})

Here's the documentation:

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks... For some reason I am not seeing the documentation you mentioned?
So I am just a bit confused in that example.... If you define fieldnames as ['first_name', 'last_name'], then why do you need to tell it to write the name of each field before the data?
You're specifying which column each piece of data goes into by column name for each row. So, for example, writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) is specifying that "Baked" goes in the First_name column and that "Beans" goes in the last name column.
Just to be extra clear on this... fieldnames = ['first_name', 'last_name'] is a List of column names (header names). What's being passed to writerow is an Dictionary {'first_name': 'Baked', 'last_name': 'Beans'}. You're NOT telling to to write the name of each field before the data. You ARE specifying which field each piece of data belongs to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.