English
Tamil Nadu Board of Secondary EducationHSC Science Class 12

Write the different methods to read a File in Python.

Advertisements
Advertisements

Question

Write the different methods to read a File in Python.

Answer in Brief
Advertisements

Solution

There are two ways to read a CSV file.

  1. Use the CSV module’s reader function
  2. Use the DictReader class.

CSV module’s reader function:

  • We can read the contents of the CSV file with the help of CSV. reader() method.
  • The reader function is designed to take each line of the file and make a list of all columns.
  • Using this method one can read data from CSV files of different formats like quotes (” “), pipe (|), and comma (,).

Syntax for CSV.reader(): .
CSV.reader( fileobject,delimiter,fmtparams)
where

  • file object: passes the path and the mode of the file
  • delimiter: an optional parameter containing the standard dilects like |, etc can be omitted.
  • Fmtparams: optional parameter which helps to override the default values of the dialects like skipinitialspace, quoting, etc. can be omitted.

Program:

#importing csv
import csv
#opening the csv file which is in different
location with read mode
with opent(‘c.\ \pvprg\ \samplel-csv’, ‘r’) as F:
#other way to open the file is f= (‘c:\ \
pyprg\ \ samplel.csv’, ‘r’)
reader = csv.reader(F)
#printing each line of the Data row by row
print(row)
F.close()

Output:

[‘SNO’, ‘NAME’, ‘CITY’]
[‘12101’, ‘RAM’, ‘CHENNAI’]
[‘12102’, ‘LAVANYA’, ‘TIRCHY’]
[‘12103’, ‘LAKSHMAN’, ‘MADURAI’]

Reading CSV File into A Dictionary:

  • To read a CSV file into a dictionary can be done by using DictReader class of CSV module which works similar to the reader() class but creates an object which maps data to a dictionary.
  • The keys are given by the field names as parameters.
  • DictReader works by reading the first line of the CSV and using each comma-separated value in this line as a dictionary key.
  • The columns in each subsequent row then behave like dictionary values and can be accessed with the appropriate key (i.e. fieldname).
import csv
filename = ‘c:\\pyprg\ \sample8.csv’
inputfile =csv.DictReader( opet(filename’r’))
for row in inputfile:
print(dict(row)) #dict() to print data

Output:

{‘ItemName’: ‘Keyboard ” ‘Quantity’: ’48’}
{‘ItemName ‘: ‘Monitor: ‘Quantity’: ’52’}
{‘ItemName ‘: ‘Mouse ” ‘Quantity’: ’20’}

shaalaa.com
Read and Write a CSV File Using Python
  Is there an error in this question or solution?
Chapter 13: Python and CSV files - Evaluation [Page 266]

APPEARS IN

Samacheer Kalvi Computer Science [English] Class 12 TN Board
Chapter 13 Python and CSV files
Evaluation | Q 3. | Page 266
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×