×

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

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Add in Dictionary Python

Dictionary in python: Dictionaries are a useful data configuration for storing information in Python because they can mimic real-world data arrangements where a particular value exists for a particular key. The...

4 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 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.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

AES CTR Python

Python Programming Language  Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

List Subtract in Python

The List is one of the most unique Data Structures in Python. It is generally used to store multiple values in just one single variable. It is one of the...

4 minutes read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python Statistical Module

Python Statistical Module The Python statistical module provides various functions that we can use in our Python program, to perform mathematical statistics operations on the numerical data given to us. The...

8 minutes read.