1

I'm modifying a CSV file with two fieldnames and I would like to add a string to the end of each row under an additional fieldname. I've figured out how to add the fieldname, but not how to add things to it. It seems like it should be simple, but I'm stumped.

import csv

with open('test2l.csv', 'r') as inny:
    reader = csv.DictReader(inny)

    with open('outfile.csv', 'w') as outty:
        fieldnames = ["Genus", "Species", "Source"] 
        writer = csv.DictWriter(outty, fieldnames = fieldnames)
        writer.writeheader()

        for record in reader:
             g = record['Genus']
             s = record['Species']

Everything I tried has just added the string to the existing string in 'Species' and I haven't been able to create a record for 'Source', I assume because it's empty.

Thanks!

1
  • 4
    just do record["Source"] = "something" then use writer.writerow(record) what's the issue? Commented Nov 17, 2017 at 20:53

2 Answers 2

1

If you haven't already, check out the documentation for csv.Reader, csv.DictReader, and csv.DictWriter.

The documentation indicates that reader objects operate on an on object using the iterator protocol. Iterating once (for row in reader:, for example) to add a "Source" exhausts the underlying iterator. Attempting to then use the same reader with a writer later would not work.

To work around this, you could create a list:

rows = list(csv.DictReader(inny))

While this exhausts the iterator, you now have a list to work with. However, this might not be ideal if the list is very long.

Another solution would be to add the Source and write the row during the same iteration:

for row in reader:
    row['Source'] = 'same string every time'
    writer.writerow(row)
Sign up to request clarification or add additional context in comments.

Comments

0

Simply write:

for record in reader:
    record["Source"] = "whateversource"

And do so before the step where you are writing to a file.`

Comments

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.