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

前端 未结 2 522
太阳男子
太阳男子 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:24

    In your code info should be a dictionary, from a list of dictionaries. It's currently a string...

    Anyway, your dataset is more suited for a simple csv.writer

    I've changed names to a list of lists, containing all the rows, changed DictWriter to writer. Then dropped writeheader for writerow with the title. Also used writerows on the list of lists for better speed (avoids a loop):

    import csv
    
    names = [ ['kisha' ,'smith'  , 'kishasmith@gmail.com', 40000  ,  '1-1-2029'   ,'janitor' ],
             # more employees here
              ]
    
    with open('employees.csv' , 'w', newline="") as employee_file:
         fieldnames2 = ['first' , 'last' , 'email' , 'salary' , 'DOB' , 'occupation']
         csvwriter = csv.writer(employee_file , delimiter = ',')
         csvwriter.writerow(fieldnames2)
         csvwriter.writerows(names)
    

    Also note that you need newline="" (python 3) or your csv file will have a blank line every other line on windows.

提交回复
热议问题