Open In App

Reading and Writing CSV Files in Python

Last Updated : 22 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separated by a delimiter(comma in most cases). To represent a CSV file, it must be saved with the .csv file extension.

Reading from CSV file

Python contains a module called csv for the handling of CSV files. The reader class from the module is used for reading data from a CSV file. At first, the CSV file is opened using the open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file object then it is read by using the reader() method of CSV module that returns the reader object that iterates throughout the lines in the specified CSV document.

Syntax:

csv.reader(csvfile, dialect='excel', **fmtparams

Note: The ‘with‘ keyword is used along with the open() method as it simplifies exception handling and automatically closes the CSV file.

Example:

Consider the below CSV file –




import csv 
    
# opening the CSV file 
with open('Giants.csv', mode ='r')as file
      
  # reading the CSV file 
  csvFile = csv.reader(file
    
  # displaying the contents of the CSV file 
  for lines in csvFile: 
        print(lines) 


Output:

[['Steve', 13, 'A'],
['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']]

Writing to CSV file

csv.writer class is used to insert data to the CSV file. This class returns a writer object which is responsible for converting the user’s data into a delimited string. A CSV file object should be opened with newline=” otherwise, newline characters inside the quoted fields will not be interpreted correctly.

Syntax:

csv.writer(csvfile, dialect='excel', **fmtparams)

csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().

  • writerow(): This method writes a single row at a time. Field row can be written using this method.
    Syntax:

    writerow(fields)
  • writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.
    Syntax:

    writerows(rows)

Example:




# Python program to demonstrate
# writing to CSV
  
  
import csv 
    
# field names 
fields = ['Name', 'Branch', 'Year', 'CGPA'
    
# data rows of csv file 
rows = [ ['Nikhil', 'COE', '2', '9.0'], 
         ['Sanchit', 'COE', '2', '9.1'], 
         ['Aditya', 'IT', '2', '9.3'], 
         ['Sagar', 'SE', '1', '9.5'], 
         ['Prateek', 'MCE', '3', '7.8'], 
         ['Sahil', 'EP', '2', '9.1']] 
    
# name of csv file 
filename = "university_records.csv"
    
# writing to csv file 
with open(filename, 'w') as csvfile: 
    # creating a csv writer object 
    csvwriter = csv.writer(csvfile) 
        
    # writing the fields 
    csvwriter.writerow(fields) 
        
    # writing the data rows 
    csvwriter.writerows(rows)


Output:

python-write-to-csv

We can also write dictionary to the CSV file. For this the CSV module provides the csv.DictWriter class. This class returns a writer object which maps dictionaries onto output rows.

Syntax:

csv.DictWriter(csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args, **kwds)

csv.DictWriter provides two methods for writing to CSV. They are:

  • writeheader(): writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.

    Syntax:

    writeheader()
    
  • writerows(): writerows method simply writes all the rows but in each row, it writes only the values(not keys).

    Syntax:

    writerows(mydict)
    

Example:




# importing the csv module 
import csv 
    
# my data rows as dictionary objects 
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'}, 
         {'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'}, 
         {'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'}, 
         {'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'}, 
         {'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'}, 
         {'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}] 
    
# field names 
fields = ['name', 'branch', 'year', 'cgpa'
    
# name of csv file 
filename = "university_records.csv"
    
# writing to csv file 
with open(filename, 'w') as csvfile: 
    # creating a csv dict writer object 
    writer = csv.DictWriter(csvfile, fieldnames = fields) 
        
    # writing headers (field names) 
    writer.writeheader() 
        
    # writing data rows 
    writer.writerows(mydict) 


Output:

python-csv



Similar Reads

Reading and Writing XML Files in Python
Extensible Markup Language, commonly known as XML is a language designed specifically to be easy to interpret by both humans and computers altogether. The language defines a set of rules used to encode a document in a specific format. In this article, methods have been described to read and write XML files in python. Note: In general, the process o
6 min read
Reading and Writing to text files in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character ('
9 min read
Reading CSV files in Python
A CSV (Comma Separated Values) file is a form of plain text document that uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fields, divided by commas. It is the most popular fil
5 min read
Writing CSV files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
8 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Reading and Writing JSON to a File in Python
The full form of JSON is Javascript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Reading and Writing lists to a file in Python
Reading and writing files is an important functionality in every programming language. Almost every application involves writing and reading operations to and from a file. To enable the reading and writing of files programming languages provide File I/O libraries with inbuilt methods that allow the creation, updation as well and reading of data fro
4 min read
Uploading and Reading a CSV File in Flask
Flask is a flexible, lightweight web-development framework built using python. A Flask application is a Python script that runs on a web server, which listens to HTTP requests and returns responses. It is designed for simple and faster development. In this article, let's upload a CSV (Comma-Separated Values) file and read the contents of the file o
3 min read
Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg