0

I have a code and a when i run it it adds information to csv file but every time it adds something new it skips a line. How to stop it?

import csv
if group == '1':
    with open('class1.csv', 'a') as csvfile:
        fieldnames = ['Forename', 'Surname', 'Score']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'Forename': name, 'Surname': name1, 'Score':score})
elif group == '2':
    with open('group1.csv', 'a') as csvfile:
        fieldnames = ['Forename', 'Surname', 'Score']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'Forename': name, 'Surname': name1, 'Score':score})
elif group == '3':
    with open('class3.csv', 'a') as csvfile:
        fieldnames = ['Forename', 'Surname', 'Score']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'Forename': name, 'Surname': name1, 'Score':score})
martineau
  • 119,623
  • 25
  • 170
  • 301
user4703104
  • 1
  • 1
  • 1

2 Answers2

0

I think you missed writer.writeheader in every if and elif conditions

if group == '1':
    with open('class1.csv', 'a') as csvfile:
        fieldnames = ['Forename', 'Surname', 'Score']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader() #you missed it
        writer.writerow({'Forename': 'name', 'Surname': 'name1', 'Score':'score'})
        #rest of code
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • When _appending_ to an existing csv file, you generally would not want to write the header since presumably there already is one. – martineau Mar 23 '15 at 13:24
0

(Assuming you're in Python 3), each time you call:

with open('mycsv.csv', 'a') as csvfile:

if you're on a Windows machine, try:

with open('mycsv.csv', 'a', newline='') as csvfile:

Edit: explanation / clarification

Per Python's documentation on csv writer,

If csvfile is a file object [meaning, if the file you passed to csv writer is called csvfile], it should be opened with newline='' ...

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms [such as Windows] that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

As martineau pointed out, you can avoid this issue in Python 2 by writing to the file in byte mode ('ab', or 'wb'). Python 3's csv module likes to work with strings, not bytes. Therefore, it should be opened in text mode (either 'w', or 'a').

user3194712
  • 1,655
  • 2
  • 10
  • 9
  • For Python 2 use `with open('mycsv.csv', 'ab') as csvfile:`. I'll upvote your answer if you edit it and explain what's causing the problem. – martineau Mar 23 '15 at 13:32