How to write to a CSV file in Python?

What is a CSV file

A CSV (Comma Separated Values) is a simple file format that stores data in a tabular form such as spreadsheets and databases. You can easily read/write data to a CSV file via a Python program. Each line of the file represents a single row of records.

CSV module in Python

The inbuilt module provides read, write and other manipulation operations to work with CSV files. The csv package provides two classes for writing csv files:

  • writer class
  • DictWriter class

How to write to a csv file using csv.writer in Python

You can create and write into the file with the following lines of code:

import csv

Columns = [‘Team’, ‘Number_of_wins’, ‘Runner_Ups’]

rows = [ [‘Brazil’, ‘5’, ‘2’],

[‘Germany’, ‘4’, ‘4’],

[‘Italy’, ‘4’, ‘2’]]

with open(‘fifawc.csv’, ‘w’) as f:

 write = csv.writer(f)

 write.writerow(Columns)

 write.writerows(rows)

  • We have imported Python’s csv module
  • Defined columns list with column names and rows list with the values
  • Then opened file with the filename in the parameter along with write mode
  • Assigned writer object in the write.  It contains the filename alias to write the lists into the spreadsheet.
  • The writer method will create a csv file
  • Finally, we wrote in the datasheet.

writerow adds a single row and writerows adds multiple rows in to the tabular data

Syntax: csv.writer(csvfileObject, dialect=’excel’, **fmtparams)

Parameters

  • csvfileObject a csv file you want to create
  • dialect object in which you pass a set of parameters
  • fmtparams a keyword argument to override dialect argument

How to write to a csv file using csv. DictWriter in Python

DictWriter is another class of csv modules to deal with the tabular data files. Dictwriter writes the Dictionary objects into comma separated values file.

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

Methods

  • Writeheader writes first rows provided in a one-dimensional dictionary.
  • writerows(dict_A) writes multiple rows by taking a dictionary object.

See the following code:

import csv 

# my data rows as dictionary objects 

Record_dict =[{‘dept’: ‘CS’, ‘cgpa’: ‘3.0’, ‘Sname’: ‘Akhter’}, 

         {‘dept’: ‘BEE’, ‘cgpa’: ‘3.1’, ‘Sname’: ‘Hafeez’}, 

         {‘dept’: ‘CS’, ‘cgpa’: ‘3.3’, ‘Sname’: ‘Hamza’}, 

         {‘dept’: ‘Maths’, ‘cgpa’: ‘2.9’, ‘Sname’: ‘Danish’}, 

         {‘dept’: ‘BBA’, ‘cgpa’: ‘3.8’, ‘Sname’: ‘Bilal’}, 

         {‘dept’: ‘SE’, ‘cgpa’: ‘2.8’, ‘Sname’: ‘Younus’}] 

fields = [‘Sname’, ‘dept’, ‘cgpa’] 

filename = “university_records.csv”

with open(filename, ‘w’) as csvfile:

    Writer = csv.DictWriter(csvfile, fieldnames = fields) 

    Writer.writeheader() 

    Writer.writerows(Record_dict)

Writing with quotechar

Writer() has two other parameters

  1. Quotechar separates the fieldnames
  2. delimiter a delimeter between the values of rows

Consider the following example:

import csv

with open(‘HockeyWins.csv’, ‘w’, newline=”) as csvfile:

    Winwriter = csv.writer(csvfile, delimiter=’ ‘, quotechar=’|’)

    Winwriter.writerow([‘Teams’,’Total wins’])

    Winwriter.writerows([[‘Pakistan’, ‘4’],[‘Australia’, ‘3’],[‘Netherlands’, ‘3’]])

Dialects in CSV Module

Using delimiter and quotechar may make the tabular data ugly. For this, you can use dialect object to group the quote fields, which is an optional parameter.

You will change the following in the above example:

csv.register_dialect(‘myDialect’,

                     delimiter=’|’,

                     quoting=csv.QUOTE_ALL)

register_dialect creates a dialect.

Winwriter = csv.writer(file, dialect=’myDialect’)

Writing into a csv file with pandas library

from pandas import DataFrame

import csv

C = {‘ODI Bowlers’: [‘Muralitharan’,’W Akram’, ‘Waqar Younus’],

        ‘ODI Wickets’: [‘534’, ‘502’, ‘Bjarne 416’],

        ‘Team’: [‘Sri Lanka’, ‘Pakistan’, ‘Pakistan’]

    }

df = DataFrame(C, columns= [‘ODI Bowlers’, ‘ODI Wickets’, ‘Team’])

export_csv = df.to_csv (r’X:\pandaOdiWickets.csv’, index = None, header=True)

print (df)

First, we have created a panda data frame then exported it into a csv file with the to_csv function.

How to write to a csv file in python: Conclusion

Comma separated Values is a popular text format to store tabular data. Python provides csv module which you can use to read and write the data with a csv file.

Writer class allows you to read/write with the file by using a tuple or panda dataframe.

DictWriter allows you to read/write with the file by using a dictionary or panda dataframe.

Leave a Reply