[Tutor] write dictionary to file

Ian D duxbuz at hotmail.com
Fri Jun 20 10:38:52 CEST 2014


This is driving me nuts.


I have tried many different things, but I just do not understand this csv library. 


I have tried passing various parameters to the writerow method and I am really getting nowhere fast.


I just want to read from a file, join text to column and write to file. 


The writerow section I really do not understand, I copied an example as it seems to make zero sense when looking at examples or reading documentation.


I thought the csv library would simplify the task but it seems to complicate it. I do not remember having this problem with sed/awk or perl.


#so far this should read a file
#using dictreader and take a column and join some text onto it

import csv

csvfile= open('StudentListToSort.csv', newline='')
spamreader = csv.DictReader(csvfile,delimiter=',',quotechar='|')

#open a file to write to later
fields = ['user','first','last','password','year']
csvoutput = open('output.csv', 'wb+')
spamwriter = csv.DictWriter(csvoutput,fieldnames=fields, delimiter=' ')



for row in spamreader:
    if row['year'] == '40':     
        username = row['user'] 
        email = "".join([username,'@email.com]) 

        output = row['user'], row['first'],row['last'],row['password'],row['year']
        spamwriter.writerow([spamreader[fields] for fieldnames in fields])
        print(output) 		 	   		  


More information about the Tutor mailing list