2

I use DictWWriter to write data to a csv-file. The file contains empty lines between my data lines. Present data is put to the rows 1,3,5,7,9, I want to wirte them into the rows 1,2,3,4,5, no empty lines in between.

import csv

with open('example4.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name', 'Grade']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'Grade': 'B', 'first_name': 'Alex', 'last_name': 'Brian'})
    writer.writerow({'Grade': 'A', 'first_name': 'Rachael',
                    'last_name': 'Rodriguez'})
    writer.writerow({'Grade': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'})
    writer.writerow({'Grade': 'B', 'first_name': 'Jane', 'last_name': 'Loive'})

Image

3
  • 2
    What output are you getting, and what output do you expect? Commented Apr 14, 2018 at 15:53
  • Looks fine to me. What exactly is the problem? Commented Apr 14, 2018 at 15:58
  • My wish to write data to the next rows in file CSV result (current data write Row 1,3,5,7,9 in the CSV file, I hope it's written on row 1,2,3,4,5) Commented Apr 14, 2018 at 16:05

1 Answer 1

1

You could have found the answer yourself by looking into the documentation.:

csv.writer:

csv.writer(csvfile, dialect='excel', **fmtparams)
Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it should be opened with newline='' [1].

And

Footnotes

[1] (1, 2) If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms 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.

It also provides a small code example:

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.