How to add headers when creating csv file in python

时间:2019-01-18 19:09:59

标签: python-3.x

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.

1 个答案:

答案 0 :(得分:0)

使用csv模块,就很简单。在数组中定义标题,然后创建一个DictWriter,将字段名设置为数组。请参考以下代码和文档:

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

以下是文档:

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