Previous Index Next

CSV File

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. A CSV file typically stores tabular data in plain text, in which each line will have the same number of fields. A CSV file is also known as a Flat File.

The CSV file format is supported by almost all spreadsheets and database management systems, including Apple Numbers, LibreOffice Calc, Apache OpenOffice Calc and MS Excel..

In Python, The csv module implements classes to read and write tabular data in CSV format. The csv module's reader and writer objects read and write sequences Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.

csv.reader() Return a reader object which will iterate over lines in the given csvfile.
csv.dictReader() Create an object that operates like a regular reader but maps the information in each row to a dictionary whose keys are given by the fieldnames parameter.
csv.writer() Return a writer object responsible for converting the user’s data into delimited strings on the given file object.
csv.dictWriter() Create an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to file.
csvwriter.writerow() Write the parameter (row) to the writer’s file object
csvwriter.writerows() Write all elements of parameter (an iterable of row objects) to the writer’s file object.

This is a sample csv file. The first line of csv file represents a header line.

File (odi.csv)
Country,Played,Won,Lost,Tied,No Result
England,746,375,334,9,28
Australia,949,575,331,9,34
India,987,513,424,9,41

Reading data from a CSV file into a list

import csv
file = open("odi.csv","r")
myreader = csv.reader(file)

for row in myreader:
    print(row)
file.close()

Output

['Country', 'Played', 'Won', 'Lost', 'Tied', 'No Result']
['England', '746', '375', '334', '9', '28']
['Australia', '949', '575', '331', '9', '34']
['India', '987', '513', '424', '9', '41']

Skipping the first row (heading)

If you don't want to parse the first row of csv file, so you can skip it with next() method.

import csv
file = open("odi.csv","r")
myreader = csv.reader(file)
next(myreader) #skipping header
for row in myreader:
    print(row)
file.close()

Output

['England', '746', '375', '334', '9', '28']
['Australia', '949', '575', '331', '9', '34']
['India', '987', '513', '424', '9', '41']

Writing data in CSV File using list

import csv
file = open("odi.csv",'a',newline='')
cwriter = csv.writer(file)

cwriter.writerow(['Pakistan','927','486','413','8','20'])
cwriter.writerow(['Sri Lanka','852','389','421','5','37'])
file.close()

In the above program we used open function to open the file in append mode, newline='' removes blank line between each row.

Reading data from a CSV file into a Dictionary

import csv
file = open("odi.csv","r")
myreader = csv.DictReader(file)
for row in myreader:
    print(row)   
file.close()

Output

{'Country': 'England', 'Played': '746', 'Won': '375', 'Lost': '334', 'Tied': '9', 'No Result': '28'}
{'Country': 'Australia', 'Played': '949', 'Won': '575', 'Lost': '331', 'Tied': '9', 'No Result': '34'}
{'Country': 'India', 'Played': '987', 'Won': '513', 'Lost': '424', 'Tied': '9', 'No Result': '41'}

Writing data in CSV File using dictionary

import csv
file = open("odi.csv",'a',newline='')
cwriter = csv.DictWriter(file, fieldnames=['Country', 'Played', 'Won', 'Lost', 'Tied', 'No Result'])
cwriter.writerow({'Country': 'Bangladesh', 'Played': '376', 'Won': '128', 'Lost': '241', 'Tied': '0', 'No Result': '7'})
cwriter.writerow({'Country': 'Afghanistan', 'Played': '126', 'Won': '59', 'Lost': '63', 'Tied': '1', 'No Result': '3'})
file.close()

Operations on CSV File

The following program creates a csv file, add three records and display it.

import csv
# to write / add data into the CSV file
def addRecord(user,password):
    file=open('users.csv','a',newline='')
    cwriter = csv.writer(file)
    cwriter.writerow([user,password])
    file.close()

# to read data from CSV file
def readRecord():
    f=open('users.csv','r')
    creader = csv.reader(f)
    for row in creader:
        print(row[0],row[1])
    f.close()

addRecord("Neil", "123@456")
addRecord("Swati","sw@tee")
addRecord("Farida","myname@FRD")
readRecord()

Output

Neil 123@456
Swati sw@tee
Farida myname@FRD


Previous Index Next