Saturday, November 16, 2024
Google search engine
HomeLanguagesWriting CSV files in Python

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 name for this file format.

Python provides an in-built module called csv to work with CSV files. There are various classes provided by this module for writing to CSV:

  • Using csv.writer class
  • Using csv.DictWriter class

Using csv.writer class

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 csvfile 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)

Parameters:
csvfile: A file object with write() method.
dialect (optional): Name of the dialect to be used.
fmtparams (optional): Formatting parameters that will overwrite those specified in the dialect.

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:

    Writing CSV files in Python
    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

Using 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)

Parameters:
csvfile: A file object with write() method.
fieldnames: A sequence of keys that identify the order in which values in the dictionary should be passed.
restval (optional): Specifies the value to be written if the dictionary is missing a key in fieldnames.
extrasaction (optional): If a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to raise a ValueError will be raised.
dialect (optional): Name of the dialect to be used.

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

RELATED ARTICLES

Most Popular

Recent Comments