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 \r\n 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 \r\r\n on Windows after each line. Let’s see an example to understand the issue,
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,
Frequently Asked:
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.
Latest Video Tutorials