Hi I have a csv file with names and surnames and empty username and password columns. How can I use python csv to write to the columns 3 and 4 in each row, just appending to it, not overwriting anything.
-
3Remember to accept answers to your questions by clicking the check mark next to the most helpful one. You've only done this for one of your last ten questions, and several of them have good answers. You should go back and accept the best ones!agf– agf2011-08-17 17:10:59 +00:00Commented Aug 17, 2011 at 17:10
Add a comment
|
1 Answer
The csv module doesn't do that, you'd have to write it out to a separate file then overwrite the old file with the new one, or read the whole file into memory and then write over it.
I'd recommend the first option:
from csv import writer as csvwriter, reader as cvsreader
from os import rename # add ', remove' on Windows
with open(infilename) as infile:
csvr = csvreader(infile)
with open(outfilename, 'wb') as outfile:
csvw = csvwriter(outfile)
for row in csvr:
# do whatever to get the username / password
# for this row here
row.append(username)
row.append(password)
csvw.writerow(row)
# or 'csvw.writerow(row + [username, password])' if you want one line
# only on Windows
# remove(infilename)
rename(outfilename, infilename)
4 Comments
Marty
I believe
open(outfilename) should be open(outfilename, 'wb'), or perhaps open(outfilename, 'w')agf
Thanks, good catch. The
csv docs use 'wb' so I'll stick with that.Marty
The python 3.2 docs use 'w' throughout, which I suspect has something to do with how the csv module deals with str vs bytes in python 3.
agf
The poster didn't mention Python 3 so I'll assume 2.