×

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 intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

What is a Script in Python

Have you ever heard that Python is a scripting language? Or when people address a Python program file as a script? Besides programming, script generally means "a written story for...

3 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

Python maketrans() function

Introduction A static method is the string maketrans() one. It is used to make a one-to-one mapping between a string's character and its translation, i.e., to define the list of characters...

5 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 Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Python hex() function

Python hex() function The hex() function in Python  converts the specified number into a hexadecimal value. Syntax hex(x) Parameter x: The parameter represents an Integer value. Return This function Returns hexadecimal string. Example 1 # Python Program explaining # the hex() function print("The...

1 minute read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.