0

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.

1
  • 3
    Remember 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! Commented Aug 17, 2011 at 17:10

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

4 Comments

I believe open(outfilename) should be open(outfilename, 'wb'), or perhaps open(outfilename, 'w')
Thanks, good catch. The csv docs use 'wb' so I'll stick with that.
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.
The poster didn't mention Python 3 so I'll assume 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.