flybonzai
flybonzai

Reputation: 3941

DictWriter not receiving my data from DictReader

I'm reading a csv file with the first row being my header row. I've verified that the headers are being passed in correctly, but my outfile remains blank. It's not kicking up any errors.

def main():
    infile = sys.argv[1]
    outfile = sys.argv[2]
    myreader = csv.DictReader(open(infile, 'rbU'))
    for line in myreader:
        print(line['ADDR_NAME'])
    mywriter = csv.DictWriter(open(outfile, 'wb'), 
                              fieldnames=myreader.fieldnames)
    #print(mywriter.fieldnames)
    for row in myreader:
        mywriter.writerow(outfile)

Upvotes: 2

Views: 222

Answers (1)

myersjustinc
myersjustinc

Reputation: 714

You should pass a dict to mywriter.writerow in your last line, not a string (file path) as you're currently doing. See the writer docs.

If you're just trying to copy all of the lines from myreader to mywriter, you'll also want to rearrange things a bit: Open both your reader and your writer first, then merge your two for loops:

def main():
    infile = sys.argv[1]
    outfile = sys.argv[2]
    myreader = csv.DictReader(open(infile, 'rbU'))
    mywriter = csv.DictWriter(open(outfile, 'wb'),
                              fieldnames=myreader.fieldnames)
    for row in myreader:
        print(row['ADDR_NAME'])
        mywriter.writerow(row)

As Cristian mentions, it also is good practice to .close files you open, but that shouldn't be causing your problem here.

Upvotes: 3

Related Questions