Using the csv
module , Ive been trying to pass / write information from a list to a csv file in python
using the dictwriter and im getting a strange e
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.