Tamilnadu State Board New Syllabus Samacheer Kalvi 12th Computer Science Guide Pdf Chapter 13 Python and CSV Files Text Book Back Questions and Answers, Notes.

Tamilnadu Samacheer Kalvi 12th Computer Science Solutions Chapter 13 Python and CSV Files

12th Computer Science Guide Python and CSV Files Text Book Questions and Answers

I. Choose the best answer (1 Mark)

Question 1.
A CSV file is also known as a…………………… (March 2020)
a) Flat File
b) 3D File
c) String File
d) Random File
Answer:
a) Flat File

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 2.
The expansion of CRLF is
a) Control Return and Line Feed
b) Carriage Return and Form Feed
c) Control Router and Line Feed
d) Carriage Return and Line Feed
Answer:
d) Carriage Return and Line Feed

Question 3.
Which of the following module is provided by Python to do several operations on the CSV files?
a) py
b) xls
c) csv
d) os
Answer:
c) csv

Question 4.
Which of the following mode is used when dealing with non-text files like image or exe files?
a) Text mode
b) Binary mode
c) xls mode
d) csv mode
Answer:
b) Binary mode

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 5.
The command used to skip a row in a CSV file is
a) next()
b) skip()
c) omit()
d) bounce()
Answer:
a) next()

Question 6.
Which of the following is a string used to terminate lines produced by writer()method of csv module?
a) Line Terminator
b) Enter key
c) Form feed
d) Data Terminator
Answer:
a) Line Terminator

Question 7.
What is the output of the following program?
import csv
d=csv.reader(open(‘c:\PYPRG\chl3\city.csv’))
next (d)
for row in d:
print(row)
if the file called “city.csv” contain the following details
chennai,mylapore
mumbai,andheri
a) chennai,mylapore
b) mumbai,andheri
c) chennai,mumbai
d) chennai,mylapore
Answer:
b) mumbai,andheri

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 8.
Which of the following creates an object which maps data to a dictionary?
a) listreader()
b) reader()
c) tuplereader()
d) DicReader ()
Answer:
d) DicReader ()

Question 9.
Making some changes in the data of the existing file or adding more data is called
a) Editing
b) Appending
c) Modification
d) Alteration
Answer:
c) Modification

Question 10.
What will be written inside the file test, csv using the following program
import csv
D = [[‘Exam’],[‘Quarterly’],[‘Halfyearly’]]
csv.register_dialect(‘M’,lineterminator = ‘\n’)
with open(‘c:\pyprg\chl3\line2.csv’, ‘w’) as f:
wr = csv.writer(f,dialect=’M’)
wr.writerows(D)
f.close()
a) Exam Quarterly Halfyearly
b) Exam Quarterly Halfyearly
c) EQH
d) Exam, Quarterly, Halfyearly
Answer:
d) Exam, Quarterly, Halfyearly

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

II. Answer the following questions (2 Marks)

Question 1.
What is CSV File?
Answer:
A CSV file is a human-readable text file where each line has a number of fields , separated by commas or some other delimiter. A CSV file is also known as a Flat File. Files in the CSV format can be imported to and exported from programs that store data in tables, such as Microsoft Excel or OpenOfficeCalc.

Question 2.
Mention the two ways to read a CSV file using Python.
Answer:
There are two ways to read a CSV file.

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

Question 3.
Mention the default modes of the File.
Answer:
The default is reading in text mode. In this mode, while reading from the file the data would be in the format of strings.
The default mode of csv file in reading and writing is text mode.

Mode Description
Y Open a file for reading, (default)
Y Open in text mode, (default)

Question 4.
What is the use of next() function?
Answer:
#using operator module for sorting multiple columns
sortedlist = sorted (data, key=operator.itemgetter(1))

Question 5.
How will you sort more than one column from a csv file? Give an example statement.
Answer:
To sort by more than one column you can use itemgetter with multiple indices.
operator.itemgetter (1,2)
Syntax:
sortedlist = sorted( data, key=operator. itemgetter( Colnumber ),reverse=True)
Example:
data = csv.reader(open(‘c:\\ PYPRG\\sample8.csv’))
next(data) #(to omit the header)
#using operator module for sorting multiple columns
sortedlist = sorted (data, key=operator. itemgetter(1,2))

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

III. Answer the following questions (3 Marks)

Question 1.
Write a note on open() function of python. What is the difference between the two methods?
Answer:
Python has a built-in function open() to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
For Example
>>> f = openf’sample.txt”) bopen file in current directory andf is file object
>>> f = open(‘c:\ \pyprg\ \chl3sample5.csv’) #specifyingfull path
You can specify the mode while opening a file. In mode, you can specify whether you want to read ‘r’, write ‘w’ or append ‘a’ to the file, you can also specify “text or binary” in which the file is to be opened.
The default is reading in text mode. In this mode, while reading from the file the data would be in the format of strings.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like image or exe files.
f = open(“test.txt”) # since no mode is specified the default mode it is used
#perform file operations
f.close( )
The above method is not entirely safe. If an exception occurs when you are performing some operation with the file, the code exits without closing the file. The best way to do this is using the “with” statement. This ensures that the file is closed when the block inside with is exited. You need not to explicitly call the close() method. It is done internally.

Question 2.
Write a Python program to modify an existing file.
Answer:
Coding:
import csv ,
row = [‘3: ‘Meena’Bangalore’]
with opent’student.csv; ‘r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader) # list()- to store each
row of data as a list
lines [3] = row
with open (student.csv, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile)
#writerows()method writes multiple rows to a csv file
writer, writerows(lines)
readFile.close()
writeFile. close()

Original File:

Roll No Name

City

1 Harshini, Chennai
2 Adhith, Mumbai
3 Dhuruv Bangalore
4 egiste, Tirchy
5 Venkat Madurai

Modified File after the coding:

Roll No Name

City

1 Harshini, Chennai
2 Adhith, Mumbai
3 Meena Bangalore
4 egiste, Tirchy
5 Venkat Madurai

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 3.
Write a Python program to read a CSV file with default delimiter comma (,).
Answer:
Coding:
#importing csv
import csv
#opening the csv file which is in different location with read mode with opent(‘c.\\pyprg\\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′,’LAV ANYA’,’TIRCHY’]
[‘12103’, ‘LAKSHMAN’, ‘MADURAI’]

Question 4.
What is the difference between the write mode and append mode?
Answer:

write mode append mode
The write mode creates a new file. append mode is used to add the data at the end of the file if the file already exists .
If the file is already existing write mode overwrites it. Otherwise creates a new one.

Question 5.
What is the difference between reader() and DictReader() function?
Answer:

reader() DictReader() function
csv. reader and csv.writer work with list/ tuple csv.DictReader and csv.DictWriter work with dictionary.
csv. reader and csv.writer do not take additional argument. csv.DictReader and csv.DictWriter take additional argument fieldnames that are used as dictionary keys

IV. Answer the following questions (5 Marks)

Question 1.
Differentiate Excel file and CSV file.
Answer:

Excel \ csv : /                     ‘
Excel is a binary file that holds information about all the worksheets in a file, including both content and formatting CSV format is a plain text format with a series of values separated by commas.
XLS files can only be read by applications that have been specially written to read their format, and can only be written in the same way. CSV can be opened with any text editor in Windows like notepad, MS Excel, Open Office, etc.
Excel is a spreadsheet that saves files into its own proprietary format viz. xls or xlsx CSV is a format for saving tabular information into a delimited text file with extension .csv
Excel consumes-more memory while importing data Importing CSV files can be much faster, and it also consumes less memory

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 2.
Tabulate the different mode with its meaning.
Answer:

Mode Description
V open a file for reading (default)
‘W’ Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘x’ Open a file for exclusive creation. If the file already exists, the operation fails.
‘a’ Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
‘t’ Open in text mode, default
‘b’ Open in binary mode.
‘+’ Open a file for updating (reading and Writing)

Question 3.
Write the different methods to read a File in Python.
Answer:
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 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 help 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).

Program:
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’}

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 4.
Write a Python program to write a CSV File with custom quotes.
Answer:
Coding:
import csv
csvData = [[‘SNO’,’Items’], [‘l’/Pen’],
[‘2′,’Book’], [‘3′,’Pencil’]]
csv.register_dialect (‘myDialect’, delimiter = ‘ | ‘,quotechar = quoting = csv. QUOTE_ALL)
with open(‘c:\\pyprg\\ch13\\ quote. csv’, ‘w’) as csvFile:
writer = csv.writer(csvFile, dialect=’myDialect’)
writer. writerows(csvData)
print (“writing completed”)
csvFile.close()

When you open the “quote.csv” file in notepad, We get following output:

Sl.No “Items”
1 “Pen”
2 “Book”
3 “Pencil”

Question 5.
Write the rules to be followed to format the data in a CSV file.
Answer:
1. Each record (row of data) is to be located on a separate line, delimited by a line break by pressing enter key.
Example:
xxx.yyy↵(↵denotes enter Key to be pressed)

2. The last record in the file mayor may not have an ending line break.
Example:
ppp,qqq↵
yyy,xxx

3. There may be an optional header line appearing as the first line of the file with the same format as normal record lines. The header will contain names corresponding to the fields in the file and should contain the same number of fields as the records in the rest of the file.
Example:
field_name 1,field_name2,field_name3
zzz,yyy,xxx CRLF(Carriage Return and Line Feed)

4. Within the header and each record, there may be one or more fields, separated by commas. Spaces are considered part of a field and should not be ignored. The last field in the record must not be followed by a comma.
Example:
Red, Blue

5. Each field mayor may not be enclosed in double quotes. If fields are not enclosed with double quotes, then double quotes may not appear inside the fields
Example.
“Red”,”Blue”,”Green”↵      #Field data with” ‘
Black,White,Yellow   #Field data without double quotes

6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
Example:
Red, Blue, Green

7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be preceded with another double quote.
Example:
“Red,” “Blue”, “Green”

12th Computer Science Guide Python and CSV Files Additional Questions and Answers

I. Choose the best answer (1 Marks)

Question 1.
CSV means ……………………… files
(a) common server values
(b) comma-separated values
(c) correct separator values
(d) constructor separated value
Answer:
(b) comma-separated values

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 2.
Abbreviation of CSV
a) Condition systematic values
b) Column separated values
c) Comma solution values
d) Comma-separated values
Answer:
d) Comma-separated values

Question 3.
csv files cannot be opened with ………………………..
(a) notepad
(b) MS Excel
(c) open office
(d) HTML
Answer:
(d) HTML

Question 4.
Which of the following can protect if the data itself contains commas in a CSV file?
a) ”
b) ,,
c) ” ”
d) ‘
Answer:
c) ” ”

Question 5.
In a CSV file, each record is to be located on a separate line, delimited by a line break by pressing
a) Enter key
b) ESV key
c) Tab key
d) Shift key
Answer:
a) Enter key

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 6.
Find the wrong statement.
(a) csv files can be opened with any text editor
(b) Excel files can be opened with any text editor
Answer:
(b) Excel files can be opened with any text editor

Question 7.
…………………… built-in function is used to open a file in Python.
a) readfn ()
b) open ()
c) reader ()
d) openfile ()
Answer:
b) open ()

Question 8.
…………… mode can be used when CSV files dealing with non-text files.
a) Write mode
b) Binary mode
c) Octal mode
d) Write mode
Answer:
b) Binary mode

Question 9.
The default file open mode is ……………….
a) rt
b) x
c) a
d) rw
Answer:
a) rt

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 10.
Any field containing a newline as part of its data should be given in ……………………..
(a) quotes
(b) double-colon
(c) colon
(d) double quotes
Answer:
(d) double quotes

Question 11.
…………………..function is designed to take each line of the file and make a list of all columns?
a) read ()
b) reader ()
c) row ()
d) list ()
Answer:
b) reader ()

Question 12.
…………………. describes the format of the CSV file that is to be read.
a) line space
b) dialect
c) whitespace
d) delimiter
Answer:
b) dialect

Question 13.
Find the correct statement
(I) The last record in the file may or may not have an ending line break
(II) Header is a must with the same format as record lines.
(a) (I) is true, (II) is False
(b) (I) is False, (II) – True
(c) (I), (II) – both are true
(d) (I), (II) – both are false
Answer:
(a) (I) is true, (II) is False

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 14.
……………. is used to add elements in CSV.
a) update ()
b) write ()
c) append ()
d) addition ()
Answer:
c) append ()

Question 15.
In CSV file,………………… function is used to sort more than one column.
a) sorter ()
b) multiplesort ()
c) itemsort ()
d) morecolumns ()
Answer:
a) sorter ()

Question 16.
In open command, file name can be represented in ………………………
(a) ” ”
(b) ”
(c) $
(d) both a & b
Answer:
(d) both a & b

Question 17.
………………… method writes a row of data into the specified CSV file.
a) rows ()
b) writerow ()
c) row_data ()
d) row_write ()
Answer:
b) writerow ()

Question 18.
……………. Action is used to print the data in dictionary form; t without order.
a) diet ()
b) dictionarys ()
c) read_dict ()
d) print_dict ()
Answer:
a) diet ()

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 19.
…………………method will free up the resources that were tied with the file.
a) freeup ()
b) open_res ()
c) resource_close ()
d) close ()]
Answer:
d) close ()]

Question 20.
In-text mode, while reading from the file the data would be in the format of ……………………..
(a) int
(b) float
(c) char
(d) strings
Answer:
(d) strings

Question 21.
CSV files are saved with extension
a) .CV
b) .CSV
c) .CVSC
d) .CSE
Ans :
b) .CSV

Question 22.
……………. command arranges a CSV file list value in descending order
a) listname.sort ()
b) listname.ascd ()
c) list_name. sort(reverse))
d) sorting ()
Answer:
c) list_name. sort(reverse))

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 23.
A ……………….. is a string used to terminate lines produced by the writer.
a) Linefeed
b) Delimiters
c) Line Terminator
d) SingleQuotes
Ans:
c) Line Terminator

Question 24.
Which format is not allowed to read data from cav files?
(a) quotes
(b) pipe
(c) comma
(d) Asterisk
Answer:
(d) Asterisk

II. Answer the following questions (2 and 3 Marks)

Question 1.
Compare text mode and binary mode.
Answer:

Text mode Binary mode
The default is reading in text mode. Binary mode returns bytes.
In this mode, while reading from the file the data would be in the format of strings. This is the mode to be used when dealing with non-text files like image or exe files

Question 2.
What is the syntax for csv.reader( )?
Answer:
The syntax for csv.reader( ) is
where csv.reader(fileobject,delimiter,fmtparams)
file object – passes the path and the mode of the file
delimiter – an optional parameter containing the standard dialects 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.

Question 3.
What is the use of the CSV file?
Answer:

  • CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
  • Since they’re plain text, they’re easier to import into a spreadsheet or another storage database, regardless of the specific software

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 4.
Define: Garbage collector
Answer:
Python has a garbage collector to clean up unreferenced objects but, the user must not rely on it to close the file.

Question 5.
How to read from CSV file that contains space at the beginning using register dialect() method?
Answer:

  • The whitespaces can be removed, by registering new dialects using csregister, dialect () class of csv module.
  • A dialect describes the format of the csv file that is to be r 4, In dialects the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.

Question 6.
Define dialect.
Answer:

  • A dialect is a class of csv module which helps to define parameters for reading and writing CSV.
  • It allows to create, store, and re-use of various formatting parameters for data.

Question 7.
Compare: sort() and sorted ().
Answer:

  • The sorted () method sorts the elements of a given item in a specific order – ascending or descending.
  • sort () method performs the same way as sorted ().
  • Only difference, sort ( ) method doesn’t return any value and changes the original list
    itself. ‘

Question 8.
Explain How to read CSV file into a dictionary?
Answer:

  • 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 fieldnames as parameter.

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 9.
What are the different formats to create csv files?
Answer:

  1. CSV file – data with default delimiter comma (,)
  2. CSV file – data with Space at the beginning
  3. CSV file – data with quotes
  4. CSV file – data with custom Delimiters

Question 10.
Give the differences between writerow() and writerows() method.
Answer:

writerow() writerows()
The writerow() method writes one row at a time. writerows() method writes all the data at once to the new CSV file.
The writerow() method writes one-dimensional data. The writerows() method writes multi-dimensional data.

Question 11.
Define: Modification
Answer:
Making some changes in the data of the existing file or adding more data is called a modification.

Question 12.
Write a note on Line Terminator.
Answer:

  • A-Line Terminator is a string used to terminate lines produced by the writer.
  • The default value is \r or \n. We can write a csv file with a line terminator in Python by registering new dialects using csv. register_dialect () class of csv module.

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 13.
Explain How to write Dictionary into CSV file with custom dialects?
Answer:
Coding:
import csv
csv.registecdialect(‘myDialect’, delimiter = ‘I; quoting=csv.QUOTE_ALL)
with open(‘c:\\pyprg\\chl3\\ vgrade.
csv, ‘w’) as csvfile
fieldnames = [‘Name’, ‘Grade’]
writer = csv. Diet Writer (csvfile, fieldnames = fieldnames, dialect =”myDialect”)
writer.writeheader()
writer.writerows([{‘Grade’: ‘B’, ‘Name’: Anu’},
{‘Gra dee:’ ‘nA/ ‘Name’: ‘Beena,’}
{Grade’: ‘C: ‘Name’: ‘Tarun’}])
print(“writing completed”)

“Name” “Grade”
“Anu” “B”
“Beena” “A”
“Tarun” “C”

Question 14.
How will you create CSV in text editor?
Answer:

  • To create a CSV file in Notepad, First open a new file using
    File → New or Ctrl +N
  • Then enter the data separating each value with a comma and each row with a new line.
  • Example: consider the following details
    Topic1, Topic2, Topic3
    one, two, three
    Example1, Example2, Example3
  • Save this content in a file with the extension.csv.

Question 15.
Explain how to create a new normal CSV file to store data
Answer:

  • The csv.writer() method returns a writer object which converts the user’s data into delimited strings on the given file-like object.
  • The writerow() method writes a row of data into the specified file.
  • The syntax for csv.writer() is csv. writer(fileobject,delimiter,fmtparams)
    where,
Fileobject: 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 help to override the default values of the dialects like skipinitialspace, quoting etc. can be omitted.

Coding:
import csv
csvData = [[‘Student’, ‘Age’], [‘Dhanush’, ’17’], [‘Kalyani’, ’18’], [‘Ram’, ’15’]]
with open(‘c:\ \ pyprg\ \chl3\ \ Pupil.csv’, ‘w’) as CF:
writer = csv.writer(CF)
# CF is the file object
writer.writerows(csvData)
# csvData is the List name
CF.close()

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 16.
Explain how to write CSV Files With Quotes
Answer:
We can write the csv file with quotes, by registering new dialects using
csv.register_dialect() class of csv module.

Coding:
import csv
info = [[‘SNO’, ‘Person’, ‘DOB’],
[‘1′,’Madhu’, ’18/12/2001′],
[‘2’, ‘Sowmya’,’19/2/1998′],
[‘3’, ‘Sangeetha’,’20/3/1999′],
[‘4’, ‘Eshwar’, ’21/4/2000′],
[‘5’, ‘Anand’, ’22/5/2001′]]
csv.register_
dialect(‘myDialect’,quoting=csv.QUOTE_ALL)
with open(‘c:\ \ pyprg\ \ chl3\ \ person, csv’, ‘w’) as f:
writer = csv.writer(f, dialect=’myDialect,)
for row in info:
writer.writerow(row)
f.close()

When you open “person.csv” file, we get following output:
” SNO”,” Person” /’DOB”
“l”,”Madhu”,”18/12/2001″
“2”,”So wmya”,”19/2/1998″
” 3″,” Sangeetha” ,”20/ 3/1999″
“4”/’Eshwar”/’21/4/2000″
“5”/’Anand”,”22/5/2001″

III. Answer the following questions (5 Marks)

Question 1.
Explain how to read a specific column in a CSV file.
Answer:
Coding for printing the selected column:
import csv
#opening the csv file which is in different location with read mode f=open(“c:\\pyprg\\13ample5.csv”/r/) #reading the File with the help of csv. reader()
readFile=csv.reader(f)
#printing the selected column
for col in readFile:
print col[0],col[3]
f.close ()

Sample5.csv File in Excel

A B C D
item Name Cost-Rs Quantity Profit
Keyboard 480 12 1152
Monitor 5200 10 10400
Mouse 200 50 2000

OUTPUT

item Name Profit
Keyboard 1152
Monitor 10400
Mouse 2000

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 2.
Explain how to read the CSV file and store it in a list.
Answer:
Coding for reading the CSV file and store it in a list:
import csv
# other way of declaring the filename
inFile= ‘c:\\pyprg\\sample.csv’
F=open (inFile/ r’)
reader = csv.reader(F)
# declaring array
array Value = [ ]
# displaying the content of the list for row
in reader:
arr ay Value. append (row)
print(row)
F.close()
OUTPUT:
[‘Topic1’, ‘Topic2’, ‘Topic3’]
[‘ one’, ‘two’, ‘three’]
[‘Example!.’, ‘Example2’, ‘Example3’]

Question 3.
Explain how to read the CSV file and sort the data in a particular column.
Answer:
Coding for reading the CSV file and sort the data in a particular column:
# sort a selected column given by user
leaving the header column
import csv
# other way of declaring the filename
inFile= ‘c:\\pyprg\\sample6.csv’
# opening the csv file which is in the same location of this
python file
F=open(inFile:r’)
# reading the File with the help of csv. readerO
reader = csv.reader(F)
# skipping the first row(heading)
next(reader)
# declaring a list
array Value = [ ]
a = int(input (“Enter the column number 1 to 3:-“))
# sorting a particular column-cost
for row in reader:
arrayValue.append(row[ a])
array Value, sort ()
for row in arrayValue:
print (row)
Eclose ()
OUTPUT:
Enter the column number 1 to 3:- 2
50
12
10

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 4.
Explain how to read CSV file with a line Terminator.
Answer:
Coding:
import csv
Data = [[‘Fruit’, ‘Quantity’], [Apple, ‘5’],
[Banana, ‘7’]’ [‘Mango: ‘8’]]
csv.register_dialect(‘myfrialect; delimiter = ‘ |’, lineterminator = ‘\n’)
with open(‘ c: \ \ py pr g\ \ ch3\ \ line .csv: ‘w’) as f:
writer = csv.writer(f, dialect=’myDialect’)
writer.writerows(Data)
f.close ()
Output:

Fruit Quantity
Apple 5
Banana 7
Mango 8

Samacheer Kalvi 12th Computer Science Guide Chapter 13 Python and CSV Files

Question 5.
Write a program to set data at runtime and writing it in a CSV file.
Answer:
Coding:
import csv
with open (‘c\\pyprg\\ch13\\
vdynamicfile.csv’, ‘w’) as f:
w = csv.writer(f)
ans= ‘y’
while (ans==’y’):
name=input (” Name?:”)
date=input(“Date of birth:”)
Place=input (“Place:”)
W.writerow([name, date, place])
ans=input(“Do you want to enter more y/n?:”)
F=open(‘c:\ \ pyprg\ \ chl3\ \ dynamicfile. csv”,r’)
reader=csv.reader (F)
for row in reader:
print (row)
F.close()
OUTPUT:
Name?: Nivethitha
Date of birth: 12/12/2001
Place: Chennai
Do you want to enter more y/n?: y
Name?: Leena
Date of birth: 15/10/2001
Place: Nagercoil
Do you want to enter more y/n?: y
Name?: Padma
Date of birth: 18/08/2001
Place: Kumbakonam
Do you want to enter more y/n?: n
[‘Nivethitha’, ’12/12/2001′, ‘Chennai’]
[]
[‘Leena’, ’15/10/2001′, ‘Nagercoil’]
[]
[‘Padma’, ’18/08/2001′, ‘Kumbakonam’]