1

Ok I acknowledge that my question might duplicate this one but I have going to ask anyways 'cause although the ultimate goals are similar, the python code in use seems quite different.

I often have a list of students to create user accounts for. For this, I need to generate UserId's of the format

 `Lastname[0:6].capitalize() + Firstname[0].capitalize()` 

or six characters from the last name and First initial. I'd like to automate this with a python script reading from one .csv file containing firstname / lastname and writing firstname lastname userid to a different csv.

Here is my code, which almost works but I am having difficulty with the write rows to .csv part at the end:

import csv



input_file = csv.DictReader(open("cl.csv"))


index=0
fldnms=input_file.fieldnames
fldnms.append('UserName')
print fldnms

for row in input_file:
    index+=1
    UserID=(row["Last"][0:6].capitalize() + row["First"][0].capitalize())
    row['UserName'] = UserID
    print index, row["Last"], row["First"], row["UserName"]



with open("users.csv",'wb') as out_csv:
    dw = csv.DictWriter(out_csv, delimiter=',', fieldnames=fldnms)
    dw.writerow(dict((fn,fn) for fn in fldnms))
    for row in input_file:
        dw.writerow(row)

Advice / thoughts welcomed.

Thanks,

Brian H.

Community
  • 1
  • 1
Uxhamby
  • 33
  • 5
  • Can you expound what the "difficulty with the write rows to .csv part" means? Perhaps you could give a sample of the output that you are currently getting. Also, try `dw.writerow(fldnms.iteritems())`. – alacy Feb 16 '15 at 16:32

1 Answers1

1

I went back to this after a good nights sleep and fwiw, here is the working version:

'''
Reads cl.csv (client list) as firstname lastname list with header

Writes users.csv as lastname firstname userid list w/o header
'''
import csv

INfile=open("..\cl_old.csv")
input_file = csv.DictReader(INfile, delimiter=' ')


fldnms={}
#print type (fldnms)
fldnms= input_file.fieldnames
fldnms.append('UserName')
#print type (fldnms)
#print (fldnms["Last"],fldnms["First"],fldnms["UserName"])
index =0


OUTfile=open("users.csv",'wb')
dw = csv.DictWriter(OUTfile, delimiter=',', fieldnames=fldnms)
dw.writerow(dict((fn,fn) for fn in fldnms))


for row in input_file:
    index+=1
    UserID=(row["Last"][0:6].capitalize() + row["First"][0].capitalize())
    row['UserName'] = UserID
    print index, row["Last"], row["First"], row["UserName"]
    dw.writerow(row)

INfile.close()
OUTfile.close()

cl.csv contains a list of first, last name pairs. Results are stored in users.csv as names, userid.

I did this as an exercise in python as excel will do this in a single instruction.

=CONCATENATE(LEFT(A2,6),LEFT(B2,1))

Hope this is of interest.

BJH

Uxhamby
  • 33
  • 5