1

I have this CSV with me called task2.csv. The header is :Item and Description. I am trying to add " i", " ink" to this csv using following csv python script. but it is adding to a wrong column and modify the last field. Please help me make my script start from a fresh new row.

Things I tried:

  • save the csv with pointer to the new row
  • wrote twice ( the second time write function was called it worked correctly. the first write still modifies the last row but second write writes to the new row.
  • checked stack overflow and modified the according to few suggestions ( Use dictReader and dictWriter) still did not work

My Code:

import csv

def readCsv(file):
    dict = {}
    with open(file) as csvdata:
        csvReader = csv.DictReader(csvdata)
        for row in csvReader:
            print row['item'], row['description']

def writeCsv(file, field):
    fieldnames = ['item', 'description']
    with open(file, 'a') as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writerow({'item': 'i', 'description': 'ink'})

writeCsv("task2.csv", "a")
readCsv("task2.csv")

ORGINAL CSV:

enter image description here

MODIFIED CSV:

enter image description here

2
  • why have you tagged both python-2.7 and python-3.x? Commented Apr 2, 2018 at 19:20
  • because it wont let me post my question unless I find another tag Commented Apr 2, 2018 at 19:26

1 Answer 1

1

I could reproduce the issue.

Reason : Your CSV last row is not complete ; The last line is not ended with 'new line` character i.e \n

and to be on safer side chanage writer = csv.DictWriter(f, fieldnames=fieldnames) to

writer = csv.DictWriter(f, fieldnames=fieldnames, lineterminator="\n")

Open csv in notepad, press Enter after hati and Save

Run the program then, it should fix the issue.

Sign up to request clarification or add additional context in comments.

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.