How to write information from a list to a csv file using csv DictWriter?

前端 未结 2 523
太阳男子
太阳男子 2021-01-27 08:40

Using the csv module , Ive been trying to pass / write information from a list to a csv file in pythonusing the dictwriter and im getting a strange e

2条回答
  •  长情又很酷
    2021-01-27 09:15

    writerow() function of the csv.DictWriter class expects the parameter as dict, whereas you are passing string to it. It is clearly mentioned in csv.DictWriter document which says:

    Create an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

    In order to make it work, pass the dict object (with the mapping between the csv headers and the corresponding column value). For example:

    import csv
    
    names = ['kisha' ,'smith'  , 'kishasmith@gmail.com', 40000  ,  '1-1-2029'   ,'janitor' ]
    fieldnames2 = ['first' , 'last' , 'email' , 'salary' , 'DOB' , 'occupation']
    
    # for creating the dictionary object mapping "names" and "fieldnames2"
    my_names_dict = dict(zip(fieldnames2, names))
    
    with open('/path/to/my_file.csv' , 'w')as employee_file:
         csvwriter = csv.DictWriter(employee_file , fieldnames = fieldnames2 , delimiter = ',')
         csvwriter.writeheader()
         csvwriter.writerow(my_names_dict)
    

    Above code will create a file /path/to/my_file.csv with the content as:

    first,last,email,salary,DOB,occupation
    kisha,smith,kishasmith@gmail.com,40000,1-1-2029,janitor
    

提交回复
热议问题