0% found this document useful (0 votes)
9 views4 pages

Chapter 13 (Python and CSV File)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 4

Chapter 13 (PYTHON AND CSV FILE)

Section B
1.What is CSV File?
* 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 that can be imported to and exported from programs that
store data in tables, such as Microsoft Excel or OpenOfficeCalc.

2.Mention the two ways to read a CSV file using Python.


Refer book page no: 232 (13.7)

3.Mention the default modes of the File.


* The default is reading (‘r’) in text mode.
* In this mode, while reading from the file the data would be in the format of strings.

4. What is use of next() function?


* “next()”command is used to avoid or skip the first row or row heading.
* Example: While sorting the row heading is also get sorted, to avoid that the first is skipped using
next().
* Then the list is sorted and displayed.

5. How will you sort more than one column from a csv file? Give an example statement.
* To sort by more than one column you can use itemgetter with multiple indices.
Syntax: operator.itemgetter(col_no)
Example: sortedlist = sorted (data, key=operator.itemgetter(1))

Section – C
1. Write a note on open() function of python. What is the difference between the two
methods?
* 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 = open(“Sample.txt”)
*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 “with” statement.
*This ensures that the file is closed when the block inside with is exited.
Example: with open(“text.txt”,’r’) as f:

2. Write a Python program to modify an existing file.


* In this program, the third row of “student.csv” is modified and saved.
* First the “student.csv” file is read by using csv.reader() function.
* Then, the list() stores each row of the file.
* The statement “lines[3] = row”, changed the third row of the file with the new content in “row”. *
The file object writer using writerows (lines) writes the values of the list to “student.csv” file.
PROGRAM:
student.csv
import csv
row = [„3‟, „Meena‟,‟Bangalore‟]
with open(„student.csv‟, „r‟) as readFile:
reader = csv.reader(readFile)
lines = list(reader)
lines[3] = row
with open(„student.csv‟, „w‟) as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()

3.Write a Python program to read a CSV file with default delimiter comma (,).
import csv
with open('c:\\pyprg\\sample1.csv', 'r') as F:
reader = csv.reader(F)
print(row)
F.close()
OUTPUT: ['SNO', 'NAME', 'CITY'] ['12101', 'RAM', 'CHENNAI'] ['12102', 'LAVANYA',
'TIRUCHY'] ['12103', 'LAKSHMAN', 'MADURAI']

4.What is the difference between the write mode and append mode.

Write Mode Append Mode


• 'w' • 'a'
• Open a file for writing. • Open for appending at the end of the
file without truncating it.
• Creates a new file if it does not exist or • Creates a new file if it does not exist.
truncates the file if it exists.

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


Reader():
* 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 (,).
* csv. Reader work with list/tuple.
* Syntax: csv.reader(fileobject,delimiter,fmtparams)
DictReader():
* DictReader works by reading the first line of the CSV and using each comma separated value in
this line as a dictionary key.
* DictReader is a class of csv module is used to read a CSV file into a dictionary.
* It creates an object which maps data to a dictionary.
* csv.DictReader work with dictionary.

Section - D
3. Write the different methods to read a File in Python.
* Contents of CSV file can be read 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,
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
* The syntax for csv.reader() is csv.reader(fileobject,delimiter,fmtparams)

i) CSV file with default delimiter comma (,)


The following program read a file called “sample1.csv” with default delimiter comma (,) and print
row by row.
import csv
with open('c:\\pyprg\\sample1.csv', 'r') as F:
reader = csv.reader(F)
print(row)
F.close()

OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']

ii) CSV files- data with Spaces at the beginning

the following program read the file through Python using “csv.reader()”.
import csv
csv.register_dialect('myDialect',delimiter = ',',skipinitialspace=True)
F=open('c:\\pyprg\\sample2.csv','r')
reader = csv.reader(F, dialect='myDialect')
for row in reader:
print(row)
F.close()
These whitespaces in the data can be removed, by registering new dialects using
csv.register_dialect() class of csv module.
A dialect describes the format of the csv file that is to be read.
In dialects the parameter “skipinitialspace” is used for removing whitespaces after the delimiter.

iii) CSV File-Data With Quotes


You can read the csv file with quotes, by registering new dialects using csv.register_dialect() class
of csv module.
Here, we have quotes.csv file with following data.

SNO,Quotes
1, "The secret to getting ahead is getting started."
2, "Excellence is a continuous process and not an accident."

The following Program read “quotes.csv” file, where delimiter is comma (,) but the quotes are
within quotes (“ “).

import csv
csv.register_dialect('myDialect',delimiter = ',',quoting=csv.QUOTE_ALL,
skipinitialspace=True)
f=open('c:\\pyprg\\quotes.csv','r')
reader = csv.reader(f, dialect='myDialect')
for row in reader:
print(row)

OUTPUT:
['SNO', 'Quotes']
['1', 'The secret to getting ahead is getting started.']
['2', 'Excellence is a continuous process and not an accident.']

In the above program, register a dialect with name myDialect.


Then, we used csv. QUOTE_ALL to display all the characters after double quotes.

You might also like