×

CSV Module In Python

Introduction

CSV stands for "comma separated values". It is the most common and simple file structure used for storing and arranging tabular data. for example; a spreadsheet or database. It stores tabular data in the form of plain text. Here the commas are used to separate each column within the row and every part of the data is separated with a comma.

CSV is a simple format for data exchange as it is general and, simpler. A CSV file is represented when it is saved with .CSV file extension.

Working with Python CSV files:

Before using the functions to CSV module we have to import it using the below code:
import csv

The CSV library provides various functions to perform read and write operations in the CSV files.

Reading the CSV file:

To perform read operation in CSV file. first, we have to generate the reader object using the reader function.

The Python's built-in function open() returns a file object by which the csv file as a text file is opened then it is passed to the reader.

Here’s the employee_joining.txt file:

name, department,joining month
Raam,Accounting, November
Aakash,IT, March

Below is the code to read the above file:

import csv

with open('employee_joining.txt') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=',')

    line_count = 0

    for row in csv_reader:

        if line_count == 0:

            print(f'Column names are {", ".join(row)}')

            line_count += 1

        else:

            print(f'\t{row[0]} works in the {row[1]} department, and joined in {row[2]}.')

            line_count += 1

    print(f'Processed {line_count} lines.')

Output:

Column names are name, department, joining month

Raam works in the Accounting department, and joined in November.

Aakash works in the IT department, and joined in March.

Here, the reader returned each row is a list of string elements and it contains the data obtained by eliminating the delimiters.

Reading a CSV file as a dictionary:

We can perform the reading operation of CSV data directly with the dictionary. Here we can read the csv files using dictreader.

The results are represented as a dictionary in which the header row is placed as the key and other rows are placed as values.

Again, the input file is employee_joining.txt file:

name, department,joining month
Raam,Accounting, November
Aakash,IT, March

Code to read as a dictionary:

import csv

with open('employee_joining.txt', mode='r') as csv_file:

    csv_reader = csv.DictReader(csv_file)

    line_count = 0

    for row in csv_reader:

        if line_count == 0:

            print(f'Column names are {", ".join(row)}')

            line_count += 1

        print(f'\t{row["name"]} works in the {row["department"]} department, and joined in {row["birthday month"]}.')

        line_count += 1

    print(f'Processed {line_count} lines.')

Output is the same as before:

Column names are name, department, birthday month

Raam works in the Accounting department, and joined in November.

Aakash works in the IT department, and joined in March.

Additional Python CSV reader parameters:

Different styles of CSV files are handled by the reader object via defining optional parameters.

Some parameters are as shown below:

  • quotechar defines the character that is used to enclose fields that includes the delimiter character. quote (' " ') is the default.
  • delimiter definesthe character that is used to divide each field. comma (',') is default.
  • escapechar defines the character that is used to skip the delimiter character. no escape character is the default.

We can explore these more with the example below.

we have employee_addresses.txt file:

name,address,date joined
Raam,Lajpat nagar New Delhi, 11024, Jan 4
Satyam, Rohini New Delhi, 110085, March 2

This file is consisting of three fields which are name, address, date joined which are separated by commas.

The problem is here is that the address field data is also containing the comma to specify the zip code.

Here, three different ways are possible to overcome this problem:

by using different delimiter:

We can safely use the comma in the data itself by using the different delimiter. we can use the delimiter additional parameter to define the new delimiter.

wrapping the data in quotes:

Here, the quotechar optional parameter can be used to define that the character used for quoting. whereas that character also does not show in the data, everything is fine.

by escaping the delimiter character:

Escape characters work as same as do in format strings and it invalidates the definition of the character being escaped and this is for delimiter character.
escapechar must specify the escape character when it is used.

Writing the CSV file:

The writing of csv file can be done by using .write_row() method and a writer object.

import csv

with open('employee_file.csv', mode='w') as employee_file:

    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['Raam', 'Accounting', 'November'])

    employee_writer.writerow(['Aakash', 'IT', 'March'])

Here, while writing which character is to be used is specified by the quotechar optional character.

It returns the plaintext which shows that the file is created for reading.

Output:

Raam, Accounting, November

Aakash,IT, March

Writing of CSV file from the dictionary:

As we can read the data from the dictionary. also, we can write the data from the dictionary as well.

import csv

with open('employee_file2.csv', mode='w') as csv_file:

    fieldnames = ['emp_name', 'dept', 'birth_joining']

    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

    writer.writeheader()

    writer.writerow({'emp_name': 'Raam', 'dept': 'Accounting', 'joining_month': 'November'})

    writer.writerow({'emp_name': 'Aakash', 'dept': 'IT', 'joining_month': 'March'})

While writing a dictionary the fieldnames parameter is required.

Output:

emp_name,dept,joining_month

Raam,Accounting,November

Aakash,IT, March

Handling CSV files by using Pandas library:

Pandas is the most popular Data science library in Python. It is used for data analysis and data manipulation.

When the amount of data is large it is better to use the Pandas library to handle the CSV files.

we have to install the Pandas before using them and to

know about installation visit: How to install Pandas?

Reading CSV File by using Pandas:

The read_csv() function is employed for reading the CSV files using Pandas.

Example:

import pandas as pd

pd.read_csv("employee.csv")

This code reads the employee.csv from the current directory.

Writing CSV files by using Pandas:

The to_csv() function is employed for writing to the CSV files using Pandas. The to_csv() is DatafFrame's function.

Example:

import pandas as pd

# creating a data frame

df = pd.DataFrame([['Raam', 24], ['Aakash', 22]], columns = ['Name', 'Age'])

# writing data frame to a CSV file

df.to_csv('Age.csv')

Here the DataFrame is created by using pd.Dataframe and then to_csv() function is called for this object.

Output:

Name, Age

Raam, 24

Aakash, 22

Conclusion:

In this article, we have discussed about the Python CSV module and understood how to perform different operations for reading and write data in CSV Files.


Related Topics

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python Glob

Methods for matching files that include particular patterns in accordance with UNIX shell-related expansion rules are referred to as "glob" methods. Similar methods for finding, locating, and searching for all of...

12 minutes read.

Python Array

Python Array In the programming language or computer science, an array is defined as the form of a data structure which consists of or store collection of various types of elements...

10 minutes read.

How to Sort a String in Python?

The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally...

6 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Poolmanager in Python

Python: 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 faster way....

4 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Filter List in Python

Python: Python is one of the most used programming languages, as it is used widely in software and data analysis, web development, etc. It is said to be a user-friendly programming...

3 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

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

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.