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
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
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.