Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python csv.DictReader. Read alter dictionary then output to file

I need to read in a pipe delimited file change some fields and output. It reads in fine and I am able to change the columns. The writer part writes the header but writerows doesn’t write anything. How can I output the updated contents?

csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile
    cfile=csv.DictReader(cfile,dialect='pipe')
    fieldnames=cfile.fieldnames
    for row in cfile:
        row['address']=scrubrow(row['address']
    

    with open('c.txt','w') as outfile:
        writer=csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')
        writer.writeheader()
        writer.writerows(cfile)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cfile is an empty iterator. And you discarded all but the last row, so doing row['address']=scrubrow(row['address'] didn’t actually do anything.

The simple way to do this is to create a list and use that list:

csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile
    reader = csv.DictReader(cfile, dialect='pipe')
    fieldnames = cfile.fieldnames
    rows = []
    for row in reader:
        rows.append(scrubrow(row['address']))
    
    with open('c.txt','w') as outfile:
        writer = csv.DictWriter(outfile, fieldnames=fieldnames, dialect='pipe')
        writer.writeheader()
        writer.writerows(rows)

But this will be inefficient because it will require O(N) space. Instead, keeping only a single row in memory at a time, you could do:

csv.register_dialect('pipe',delimiter='|', quoting=csv,QUOTE_NONE)

with open('test.txt') as csvfile, open('c.txt','w') as outfile:
    reader = csv.DictReader(cfile,dialect='pipe')

    fieldnames = reader.fieldnames
    writer = csv.DictWriter(outfile,fieldnames=fieldnames,dialect='pipe')

    writer.writeheader()
    for row in reader:
        writer.writerow(scrubrow(row['address']))
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading