Explain about CSV module in Python

mahesh reddy
5 min readJan 19, 2021

--

A perfect alternative to reading CSV files is Pandas. Other ways to parse text files with libraries like ANTLR, PLY, and PlyPlus are also available. They can all handle heavy-duty decoding, and there are regular expressions you can use if basic string manipulation does not work. Here, in this article, we will check the CSV modules in Python.

A CSV file is a type of plain text file that arranges tabular data using unique structures. As it’s lightweight, easy, and general, CSV is a popular format for data interchange. Many online services allow their users to export a CSV file with tabular data from the website. CSV files can be opened in Excel, and almost all databases have a CSV file import tool. The default format is specified by information about rows and columns. Besides, to begin the next row, each row is terminated by a new line. Each column is also divided by a comma within the row.

Sample File CSV.

In the form of tables, data is also called CSV (comma-separated values) — simply “comma-separated values.” This is a text format for the presentation of tabular data. Each line of the file is a table row. A separator symbol — a comma (,), a semicolon (;) or another symbol — divides the values of individual columns. CSV can be read and interpreted by Python with ease.

Data from CSV

  • Language of Programming, Planned, Appeared, Extension
  • Python, 1991, Guido van Rossum, .python.
  • Java, 1995 James Gosling, .java
  • C++, 1983, Bjarne Stroustrup,.cpp
  • Each row, as you can see, is a new line, and each column is separated by a comma. This is an image of how a CSV file looks.

If you are interested To Learn Python you can enroll for free live demo Python Online Training

CSV Python Module

For handling CSV files, Python provides a CSV module. You need to loop through rows in the CSV to read/write data. To get data from the specified columns, you need to use the split process.

Functions for CSV module

The following functions can be found in the CSV module documentation.

Return maximum field size of csv. field size limit

  • CSV. get dialect-acquire the dialect associated with the name
  • Csv.list dialects-show all dialects reported
  • Csv.reader-reading information from a csv file
  • Csv.register dialect — the name-associated dialect
  • Csv.writer-write details into a csv file
  • Csv. unregister dialect — delete the dialect linked to the dialect registry name
  • Csv.QUOTE, ALL — Regardless of form, quote all.
  • Csv.QUOTE MINIMAL — Quote special-character fields
  • Csv.QUOTE NONNUMERIC — Quote all fields that do not contain value numbers
  • Csv.QUOTE NONE-In the production, do not quote anything

In this article, we will concentrate only on the functions of the reader and writer that allow you to edit, alter, and manipulate the data in a CSV file.

How to Read a File from CSV

You must use the reader feature to create a reader object to read data from CSV files.

The reader feature is designed to make a list of all columns by taking each row of the file. Then you have to pick the column for which you want the data for the attribute.

It sounds much more complicated than it is. Let’s take a look at this example, and we’ll find out that it’s not so difficult to work with a CSV file.

#import the modules needed

Csv import

With open(‘X:\data.csv ‘,’ rt ‘) as f:

Data = csv.reader csvreader (f)

For Data Row:

Print a Print (row)

As a dictionary, how to read a CSV

You can also use the DictReader feature to read CSV files. The results are interpreted as a dictionary in which the key is the header row, and other values are rows.

Consider the code below

#import the modules needed

CSV import

The reader = CSV.DictReader(open(“file2.csv”)))

Raw for the reader:

Print a Print (raw)

And it’s a lot simpler way to read data from a CSV file than the previous process. This is not the best way to read results, though.

How to write a file with CSV

You have to use the writer() function when you have a collection of data that you would like to store in a CSV format. You have to use the write() function to iterate the data over the rows(lines).

Consider the example that follows. We write data into a “writeData.csv” file where an apostrophe is the delimiter.

#import the modules needed

Csv import

As file: with open(‘X:\writeData.csv ‘, mode=’w’)

#way to write a csv file to

Writer.writerow([‘Language of programming ‘,’ Built by ‘,’ Appeared ‘,’ Extension ‘])

Writer.writerow([‘Python ‘,’ Guido van Rossum ‘,’ 1991 ‘,’ .py’]))

Writer.writerow([‘Java ‘,’ James Gosling ‘,’ 1995 ‘,’ .java ‘])

Author.writerow([‘C++ ‘,’ Bjarne Stroustrup ‘,’ 1985', ‘.cpp

In the csv format, the result is as follows.

Language of Programming, Planned, Appeared, Extension

Python, 1991, Guido van Rossum, .python.

Java, 1995 James Gosling, .java

C++, 1983, Bjarne Stroustrup,.cpp

CSV Files Reading with Pandas

Pandas is an open-source library that allows data manipulation in Python to be carried out. Pandas provide a simple way for data to be generated, manipulated, and deleted.

You need to install the panda’s library by using the pip install pandas command. In Windows, this command is executed in the Command Prompt when in the Terminal under Linux.

It’s very fast and easy to read the CSV into a panda data frame:

#import the modules needed

Pandas import pandas

Outcome = pandas.read CSV(‘X:\data.CSV ‘)

//Print Print (result)

Outcome:

Language of Programming, Planned, Appeared, Extension

0 Python, Guido van Rossum, 1991, .python, 1991, .python

1 Java, 1995 by James Gosling, .java

2 C++, 1983, Bjarne Stroustrup,.cpp

It’s a very helpful library. You have the same outcome in just three lines of code as before. Pandas know the column names found in the first line of the CSV, and they will be used automatically.

Writing with Pandas on CSV Files

Writing to a Pandas CSV file is as easy as reading. Here, you can persuade yourself. You must first construct a Data Frame based on the following code.

Importing Data Frame from Pandas

C = {‘Language programming’: [‘Python’,’Java’,’ C++’],,,

‘Conceived by’: [‘Guido van Rossum’, ‘James Gosling’, ‘Bjarne Stroustrup’],,’

‘Appeared’: [‘1991’, ‘1995’, ‘1985’], ‘Appeared’:

‘Extension’: [‘.py’, ‘.java’, ‘.cpp’],, ‘Extension’:

}

Df = DataFrame(C, columns= [‘Language of programming’,’ Built by’,’ Appeared’,’ Extension’])

Export csv = df.to csv (r’X:\pandaresult.csv ‘, index = Zero, header=True) # You need to write the path where the result file will be saved.

Print a Print (pdf)

The performance here is as follows.

Language of Programming, Planned, Appeared, Extension

0 Python, Guido van Rossum, 1991, .python, 1991, .python

1 Java, 1995 by James Gosling, .java

2 C++, 1983, Bjarne Stroustrup,.cpp

And the CSV file is generated at the location defined.

Conclusion

So, now you know how to use the ‘CSV’ template and read and write CSV format data as well. In software applications, CSV files are commonly used because they are simple to read and handle, and their small size makes them relatively fast for processing and transmission.

The CSV module provides several functions and classes that make it simple to read and write. The official Python documentation can be viewed and some more useful tips and modules can be found. CSV is the best way for data to be stored, accessed, and sent. It’s not so difficult to remember as it appears at the beginning. But you’ll master it with a little practice. You can also learn more about these modules through Python online training.

--

--

mahesh reddy
mahesh reddy

Written by mahesh reddy

Python certification training course will help you master the concepts and gain in-depth experience on writing Python code and packages like SciPy, Matplotlib,

No responses yet