[Tutor] write dictionary to file
Walter Prins
wprins at gmail.com
Fri Jun 20 11:42:49 CEST 2014
Hi,
On 20 June 2014 09:38, Ian D <duxbuz at hotmail.com> wrote:
> #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)
Using DictReader and DictWriter means you retrieve and provide Python
dict's when interacting with the CSV module. Maybe this is adding some
confusion? Anyhow, here's a quick&dirty example modified from the
source you posted which adds a column to an existing CSV file.
(Initially I create the CSV just using a plain CSV writer. Then that
file is read in and a column added to selected records and written out
again.)
# -*- coding: utf-8 -*-
import csv
def create_demo_file(csv_demo_filename):
csvfile=open(csv_demo_filename, 'wb')
csvw = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
csvw.writerow(['user','first','last','password','year'])
csvw.writerows([
(1, 'john', 'smith', 'LKJ£$_£(*$£', 35),
(2, 'joe', 'bloggs','5^££J"HLLDD', 40),
(3, 'alice','jones', '^%!*&^%1681', 43),
(4, 'bob', 'white', '!&££JHLKJ*F', 28),
])
csvfile.close()
def add_email_to_csv(csv_input_filename, csv_output_filename):
csvfile= open(csv_input_filename)
spamreader = csv.DictReader(csvfile)
fields = ['user','first','last','password','year', 'email']
csvoutput = open(csv_output_filename, 'wb+')
spamwriter = csv.DictWriter(csvoutput,fieldnames=fields)
spamwriter.writeheader()
for row in spamreader:
if row['year'] in ('43', '40'):
username = row['user']
row['email'] = username+'@email.com'
spamwriter.writerow(row)
csvoutput.close()
###
create_demo_file('StudentListToSort.csv')
print 'Demo input file created contents:'
print open('StudentListToSort.csv', 'r').read()
add_email_to_csv('StudentListToSort.csv', 'output.csv')
print 'Demo output file created contents:'
print open('output.csv', 'r').read()
More information about the Tutor
mailing list