×

CSV Write in Python

What is meant by CSV?

CSV stands for Comma Separated Values.

The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in spreadsheets or databases.

Spreadsheets are nothing but Excel sheets. The Excel sheets' data are categorized using the concept of Comma Separated Values, i.e., CSV.

CSV converts the data into tables so that the data can be organized and retrieval becomes easier.

Import and export of data become easier when the CSV concept is implemented. The data can be manipulated efficiently, and the reading and writing of the data can be hidden from the programmer.

As we've already discussed, CSV completely works on converting the data into tables.

Every line of the tabled data is known as Record. The files or data that are present in the records are separated by "commas" by default. As commas act as a default character for every record, Comma is said to be known as a Delimiter.

What if we don’t have CSV?

The world without CSV is just like a room without shelves. What if we have no shelves in a room? Can we be able to arrange all the things in an organized way? The answer is no. In the same way, CSV is required compulsorily in order to have organized data.

What is a CSV File?

A plain text file that is used to arrange tabular data by using a specific structure is known as CSV File.

Generally, CSV performs two operations. They are listed below.

  1. Reading CSV file.
  2. Writing CSV file.

Reading or Writing CSV files can be done by using "CSV module" and "Pandas".

Now, let's discuss the Writing CSV file.

Writing CSV File using CSV module:

CSV module is already a part of Standard Libraries. So, we need not install the CSV module separately as we already have it in the Standard Libraries by default. You can import CSV to perform "csv write". We can declare a set, i.e., data set to create a CSV file and perform the Write operation. The data set should contain the rows in the form of a list again sub-listed by a parent list.

Let’s consider an example program:

import csv
birthday = [“Name” , “Day “ ,  “Month “ , ” Year “]
var1 = [
     [“Neo”, 30 , ”November” , 2002],
     [“Sanneh” , 02 , ”May”, 2002],
     [“Samuel” , 10 , ”November” , 2002],
     [“David”, 11, ”April” , 2003],
     [“Tara” , 31 , ”March” , 2002],
     [“Daniel” , 21 , ”May” , 2003],
     [“Joe” , 07 , ”March” , 2002],
        ]
filepath = “ C:\\birthdayblast.csv”
with open(filepath ,’w’) as remind:
	var2 = csv.writer(remind)
	var2.writerow(birthday)
	var2.writerows(var1)

The output of the written program:

Name, Day, Month, Year
Neo, 30, November 2002
Sanneh, 02, May 2002
Samuel, 10, November 2002
David, 11, April 2003
Tara, 31, March 2002
Daniel, 21, May 2003
Joe, 07, March 2002

An explanation for the program:

CSV module is imported initially as it is already present in the standard libraries. Then, a variable "birthday" is declared to list the column names of the data set. Variable "var1" is declared to list out the data entries. Then, a variable "file path" is declared to mention the file's path. The inbuilt functions are called by the variable "var2" for the other variables. Now comes the syntax of CSV write. In the syntax, 'w' indicates write CSV.

Writing CSV File using Pandas:

CSV files can also be imported with the help of pandas.It also performs Data manipulation and provides easy ways to create and delete data. Pandas is not an inbuilt package. So, it must be installed.

Let’s consider an example program:

from pandas import pa
var1 = { ‘ Movie_name ‘ : [ ‘ Bahubali ‘ , ‘ RRR ‘ , ‘ Radhe Shyam ’] ,
              ‘ Directed_by ‘ : [ ‘ Rajamouli ‘ , ‘ Rajamouli ‘ , ‘ Radha Krishna ‘],
              ‘ Release_year ‘ : [ ‘ 2017 ‘ , ‘ 2022 ‘ , ’ 2022’ ],
	}
var2 = pa( var1, columns = [“Movie_name” , “Directed_by” , “Release_year”])
filepath = “ C:\\movies.csv”
export_csv = var2.to_csv(r’filepath’, index= None, header = True)
print(var2)

The output of the written program:

Movie_name   Directed_by   Release_year
0  Bahubali    Rajamouli   2017
1  RRR    Rajamouli    2022
2  Radhe Shyam    2022

An explanation for the program:

After pandas are installed, pa is imported from pandas. A variable "var1" is declared to list the data set, whereas "var2 "lists out the columns. A variable "filepath" is set to store the file's path. The function ".to_csv()" is used to take the written data as a table. Var2 calls this function. So, all the values or data have been stored in var2. Finally, print(var2) is performed to print the data.


Related Topics

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

Python frozenset()

Python frozenset() class The frozenset() class in Python returns a new frozenset object, optionally with elements taken from iterable. Syntax class frozenset([iterable]) Parameter iterable: This parameter represents an iterable object, like list, set, tuple etc. Return This class returns an unchangeable...

1 minute read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python bytearray()

Python bytearray() Class The bytearray() class is used to return a bytearray object which is an array of the specified bytes. It gives a mutable sequence of integers in the range 0...

1 minute read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Python next() function

Python next() function The next() function in Python retrieves the next item from the iterator.  Syntax next(iterator[, default]) Parameter iterable: It is a required parameter which represents an iterable object. default: This parameter represents a default value to...

1 minute read.

Abstraction in Python

What is meant by abstraction generally? A very general notion of a thing or work is known as abstract. To be more precise, the process of having a brief idea but...

4 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.