1

I am adding a new row to a specific CSV that already exist, but for unknown reason the new row is being added along with the last row and not in a new one.

So, it's showing in CSV as:

11-07-2016,38361,9076,14487,292,741614-07-2016,38417,9767,15832,301,7416

When should be showing as:

11-07-2016,38361,9076,14487,292,7416
14-07-2016,38417,9767,15832,301,7416

My code is:

import time
import csv


today = (time.strftime("%d-%m-%Y"))
newRow = """%s,%s,%s,%s,%s,%s""" % (today, yes, ok, war, leg, noag)
fd = open('data.csv','a')
fd.write(newRow)
fd.close()

Any idea why this is happening? Thanks a lot.

3 Answers 3

2

It looks like the file doesn't have a newline at the end. Try adding one before appending the new line:

newRow = "\n%s,%s,%s,%s,%s,%s\n" % (today, yes, ok, war, leg, noag)
with open("data.csv", "a") as f:
    f.write(newRow)
Sign up to request clarification or add additional context in comments.

6 Comments

You solved his specific problem, but did this help him understand what went wrong?
actually I think I understood, adding the\n it forced the newRow to be in a new row, right? Thank you.
@Gonzalo that's right if you use the file as a text file. But if you want to use it as a csv file with the csv module you don't need to add the \n manualy.
but now the file has a empty row between each line.. it happens everytime i run the code.. so somehing must be wrong.
@Gonzalo that because you add \n at the beginning and at the end of the newRow.
|
0

Right now you are not using the csv module, just the regular write as for text file.

To treat the file as a csv change:

fd.write(newRow)

to:

csv_writer = csv.writer(fd)
csv_writer.writerow(newRow)

If you want to edit the file as a text file you should add the "new line charecter" manualy, so:

fd.write('\n' + newRow)

will work (in that case the import csv is redundant)

Comments

0
import time
import csv


today = (time.strftime("%d-%m-%Y"))
newRow = """%s,%s,%s,%s,%s,%s""" % (today, yes, ok, war, leg, noag)
with open('data.csv','a',newline='') as fd:
    writer = csv.writer(fd)
    writer.writerow(newRow)

It's writerow instead of write, it'll automatically add a new line. and newline = '' prevents your skip a line.

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.