We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

56
5.300.283,95

Cart

Quantity 19.800,00
Quantity 10.000,00
Quantity 116,00

Write to csv file without blank line in Python

In this article, we will learn how to write to a csv file without blank lines in Python.

Table Of Contents

Introduction to Problem

In Python, the writer() function of csv module controls the line endings. By default it writes the rn into the file directly. Therefore, in Python3 we must open file in untranslated text mode. It means, use the parameter newline=” with parameter ‘w’. Otherwise, it will write rrn on Windows after each line. Let’s see an example to understand the issue,

Advertisements

import csv

# A List of lists
students = [['Ritika', 27, 'Delhi', 'India'],
            ['Mark', 28, 'Sydney', 'Australia'],
            ['Suse', 29, 'Las Vegas', 'USA'],
            ['Shaun', 30, 'London', 'UK']]

# A list containing the heading of csv file
heading = ['Name', 'Age', 'City', 'Country']

with open('students.csv', 'w') as fileObj:
    writerObj = csv.writer(fileObj)
    writerObj.writerow(heading)
    writerObj.writerows(students)

It will create a csv file students.csv with four rows. If you will open this file on notepad, then it will look file. But if you will open this csv file in excel, then it will have a newline (empty line) after every row. Something like this,

Name    Age City    Country

Ritika  27  Delhi   India

Mark    28  Sydney  Australia

Suse    29  Las Vegas   USA

Shaun   30  London  UK

Solution

To write to csv without these extra newlines, we need to pass parameter newline=” in the opn() function. So, that newline after every row is controlled by csv writer only. Let’s see the solution,

import csv

# A List of lists
students = [['Ritika', 27, 'Delhi', 'India'],
            ['Mark', 28, 'Sydney', 'Australia'],
            ['Suse', 29, 'Las Vegas', 'USA'],
            ['Shaun', 30, 'London', 'UK']]

# A list containing the heading of csv file
heading = ['Name', 'Age', 'City', 'Country']

with open('students2.csv', 'w', newline='') as fileObj:
    writerObj = csv.writer(fileObj)
    writerObj.writerow(heading)
    writerObj.writerows(students)

It will create a csv file without extra newlines. Contents of the file in excel will be,

Name,Age,City,Country
Ritika,27,Delhi,India
Mark,28,Sydney,Australia
Suse,29,Las Vegas,USA
Shaun,30,London,UK

Summary

We learned how to write a csv file with extra newlines in Python.

56
5.300.283,95

Cart

Quantity 19.800,00
Quantity 10.000,00
Quantity 116,00