0% found this document useful (0 votes)
114 views78 pages

Chapter 4 File Handlinf Final (New)

File handling in Python allows programs to read from and write to files to permanently store data. There are three main types of files: text files for storing text data, binary files for storing non-text data like images, and CSV files for storing tabular data with comma-separated values. The key operations for file handling in Python are opening a file using the open() function, reading/writing data, and closing the file using the close() function. This allows data to be transferred between a program's memory and permanent file storage.

Uploaded by

HKP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views78 pages

Chapter 4 File Handlinf Final (New)

File handling in Python allows programs to read from and write to files to permanently store data. There are three main types of files: text files for storing text data, binary files for storing non-text data like images, and CSV files for storing tabular data with comma-separated values. The key operations for file handling in Python are opening a file using the open() function, reading/writing data, and closing the file using the close() function. This allows data to be transferred between a program's memory and permanent file storage.

Uploaded by

HKP
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 78

FILE HANDLING IN PYTHON

[Based on CBSE Curriculum Class-12]


Lesson - 4

2020

Presented By :
MR. M. GOVINDA RAO
PGT(Comp. Sc. )
DAV PUBLIC SCHOOL BERHAMPUR
Bhubaneswar Region, Odisha , Zone-1
Learning objective
Why need File Handling

Types of File

Python File Handling System

Practical Approach to understand the Theory


Previous Knowledge
Students will be able to Know :

 Basic knowledge of Python

 Basic knowledge of Data Files


Data files in python
WHY DATA FILES ?????????????????......
The data files are the files that stores data pertaining to
a specific application.

As we know whenever we enter data while running program,


it is not saved any where and we have to enter it again when
we run the program again. So to store required data
permanently on hard disk ( Secondary storage device) we need
to store it in file.

Note :- File is a stream or sequence of bytes/character.


Introduction Data File Handling
• We have seen yet only the transient programs. The programs which run
for a short period of time and give some output and after that their data is
disappeared. And when we again run those programs then we have to use
new data.
• This is because the data is entered in primary memory which is temporary
memory and its data is volatile.
• Those programs which are persistent i.e. they are always in running or run
for a long time then their data is stored in permanent storage (e.g.
harddisk) . If the program is closed or restarted then the data used will be
retrieved.
• For this purpose the program should have the capability to read or write
the text files or data files. These files can be saved in permanent storage.
• The meaning of File I/O (input-output) is to transfer the data from Primary
memory to secondary memory and vice-versa.

(Random Access Hard Disk


User
Memory)

Program in RAM
TYPES OF FILES
File are of Three types –
1. Text File: A Text file stores information in ASCII or Unicode characters
(The
one which we can understand very easily).In text file each line is
terminated
with a special character known as EOL(End of Line).In Python, by default,
this EOL character is the newline character(„\n‟) or carriage-return, newline
combination („\r\n‟).
2. Binary File: A binary file is just a file that contains information in the same
format in which the information is held in memory i.e the file content that is
returned to you is raw (with no translation or no specific coding. It is used
to store binary data such as images, videos audio etc.Generally numbers
are stored in binary files. In binary file,there is no delimiter to end a line.
Since they are directly in the form of binary hence there is no need to
translate them.That’s why these files are easy and fast in working.
3. The CSV is a file, it stands for Comma separated values , it is a simple file
format used to store tabular data, such as spreadsheet or database. In which each
line is a record. The record consist of fields separated by comma. it can be
Notepad file, in which each row data should be separated by comma., When you
will open in Notepad it will display normal text separated by comma. It can be
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES
Text Files Binary Files
1.Text Files are sequential files 1. A Binary file contain arbitrary
binary data
2. Text files only stores texts 2. Binary Files are used to store
binary data such as image, video,
audio, text
3. There is a delimiter EOL 3. There is no delimiter
(End of Line i.e \n)

4. Text files easy to understand 4. Binary files are difficult to


because these files are in human understand.
readable form
5. Text files are having 5. Binary files are having .dat
extension .txt extension
BASIC OPERATIONS ON FILE

Basic operations performed on a data file


are:
1. Naming a file

2. Opening a file

3. Reading data from the file

4. Writing data in the file

5. Closing a file
Operation on File Handling
Whenever we worked with Data file
in Python we have to follow sequence
 Open/Create file
 Read from/ write to file
Close file
We can do following tasks/
operation with python data files.
 Creation/opening of an existing data file.
 Reading from file.
 Writing to data file.
 Appending data(inserting data at the end
of the file)
 Inserting data(in between the file)
 Deleting data from file
 copying a file
Modification/ updation in data file
Python File Handling System
Text files in Python
Text file don’t have any specific encoding and
it can be opened in normal text editor itself.
Example :-
Web Standards : html, XML, Css, JsON etc.
 Source Code : C, app, JS, py, Java, etc.
 Documents : txt, tex, RTF etc.
Tabular Data : CSV, tsv, etc.
Configuration : ini, ctg, reg etc.
TWO METHODS TO
OPENING A TEXT FILES
Using open()
function
External File

Using with
(Secodry
Storage)

statement
OPENING A FILES USING OPEN()
• We need a file variable or file handle to work with files in Python.
• This file object can be created by using open( ) function .
• Open( ) function creates a file object, which is used later to access
the file using the functions related to file manipulation.
• Its syntax is following –
<file_object> = open(<filename>) Example: f= open(“Hello.txt”)
OR Example: f=open(“Hello.txt”,”r”)
<file_object>=open(<file_name>,<access_mode>)

External File
File Handle Mode (Secodry
of
or Path to a file a file Storage)
File object created
File handler is also know as file object is like a cursor, which defines from where
the data has to be read or written in the file
Access modes govern the type of operations possible in the opened file
Example:
• F = open(“Hello.txt”)
• The above statement opens file Hello.txt as read mode (default mode) and attaches it to file
object named F

• F = open(“myfile.txt”,’r’)
The above statement opens Hello.txt in read mode (default mode) and attaches it to file
object named F

• F= open(“C:\\Users\\DELL\\Desktop\\Hello.txt”, “r”)
The above statement opens file Hello.txt in a specific folder in read mode (default mode) and
attaches it to file object named F.
However, if you want to write with a single slash you may write in raw string that means there
is no special meaning attached to any character. as follow :

• F = open (r“C:\Users\DELL\Desktop\Hello.txt”, “r”)


Important Note :-
1) The file should exist in the same directory as the Python script,
otherwise full address of the file should be written.
2. When you open a file in read mode, the given file must exist in the folder otherwise it
will rise FileNotFoundError.
File Access Modes in Text Files
Mode Description
r To read the file which is already existing.

r+ To Read and write but the file pointer will be at the beginning of the file.

w
Only writing mode, if file is existing the old file will be overwritten else the
new file will be created.

w+ Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exists , create a new file for reading and
writing.

a
Append mode. The file pointer will be at the end of the file.
a+
Appending and reading if the file is existing then file pointer will be at the
end of the file else new file will be created for reading and writing.
Closing A Files
• A close( ) function breaks the link of file-object and
the file on the disk.
• After close( ), no task can be performed on that file
through the file-object.

File
Object
Functions used Text File
S.NO Function Syntax Use
Name
01 open() F_obj=open(“File To open or create a file in desired
name”,”mode”) mode.
02 close() F_obj=close() To close the file.

03 read() F_obj=read() OR To read all OR specified no of


F_obj=read(n) characters from the file.

04 readline() F_obj=readline() OR To read a single line OR specified


F_obj=readline(n) no of character from a line in a file.

05 readlines() F_obj=readlines() To read all lines from a file and


return it into the form of list.
06 write() F_obj=write(str) To write data( of string type) on to
the file and return the numeric.
07 writelines() F_obj=writelines(LST) To write sequence(list/tuple etc of
string in a file.
Opening & Closing
Files. . . Opened the File
Here the point is that the file “Hello.txt” which is used here is pre built
and stored in the same folder where Python is installed.

The file is closed.

Output
OPENING A FILES USING WITH STATEMENT
• This Method is very handy when you have two related operations
which you would like to execute as a pair, with a block of code in
between.
• Benefits of using with statement
 It automatically closes the file after the nested block of code
 It also handle all the exception also occurred before the end of
block.
• Its syntax is following –
with open(<filename>,< File Mode>) as <File Handle>:
For Example: External File
(Secodry
with open(“Poem.txt”,”w”) as f: Storage)
f.write( “Twinkle twinkle little star,\n”)
f.write( “How I wonder what you are,\n”)
f.write( “Up abobe the world so high,\n”)
f.write( “Like a dimond in the sky,\n”)
Reading Data from a file
We can read characters into file
by using following three method.
PYTHON
 read( ) PROGRAM
 readline()
 readlines( )
A Program read into a text file from hard disk.
read()
Reads at most n bytes;
if no n is not specified,reads the entire file.
Returns the read bytes in the form of a string.
Syntax:<Filehandle>.read([n])
Example :-
A Program to read
“Hello.txt” File

Reading First 10
character from the
“Hello.txt” File
readline()
Reads a line of input ; if n is specified reads at
most n bytes.
Returns the read bytes in the form of a string
ending with ‘\n’ character.
Returns a blank string if no more bytes are left
for reading in the file.
Syntax : <Filehandle>.readline()
For Example:-
Which can read one line
at a time from the file.
readlines()
 Reads all the lines of a text file.
 Returns in the form of list.
 Syntax : <FileHandle>.readlines()
 For Example :-

It is used to
read many
lines.

Lets Demonstrate
Read() Operation
Readline() Operation
Readlines() Operation
QUIZ TIME
Q-4. Which of the following are the attributes related to a file object?
A. closed
B. mode
C. name
D. rename
QUIZ TIME
Q-4. Which of the following are the attributes related to a file object?
A. closed
B. mode
C. name
D. rename
QUIZ TIME
Which of the following are the attributes related to a file object?
A. closed
B. mode
C. name
D. rename
How to write data in a file?
• We can write characters into file by
using following two method.
PYTHON
 write (string) PROGRAM

 writelines (sequence of lines)


While writing data in a file note the
following point :
If file doesn’t exists, it will create the new file.

If file exists, it will write the data in the file.

A Program writes into a text file in the hard disk.


write(string)
 write( ) method takes a string and writes it in the file.

For storing data, with EOL character, we have to add ‘\n’


character to the end of the string.
For storing numeric value, we have to either convert it into
string using str( ) or write in quotes..
A Program to write
in “Demo.txt”

This “Hello.txt” is created using above


The Demo.txt is created
program.
using the file

Output
writelines(sequence of lines)
writelines( ) method is used to write sequence
data types in a file (string, list and tuple etc.)

A Program to write
in “Demo.txt”

The Data.txt is created


using the file

Output
Appending data to a File
Append means to add the data at the end of file using ‘a’ mode.
A Program to
 If file doesn’t exists, it will create the new file. write in
If file exists, it will append the data at the end of a file. “Hello1.txt”

• A

Output

Output

The Hello.txt is created


using the file
Writing User Input to the File.

Taking the data from


user and writing this
data to the file
"Student.txt"

Student File is created by using


Output the above program.
Questions which can
be asked in the CBSE
CLASS XII
Board Examination.
(Text file)
Expected Board Questions ( 2 Marks)
Q1. Write a function in Python to read lines from a
text file ‘Poem.txt’ and display those lines which are
either starting with an alphabet ‘I’ or starting with an
alphabet a’.
Q2. Write a method in Python BIGLINES() to read
lines from a text file ‘Poem.txt’ and display those
lines, which are bigger than 50 characters.
Q3.Write a inmethod in Python to count the total
number of words a file.
Q4 Write a method in Python to read lines from a
text file ‘India.txt’, to find and display the occurrence
of the word ‘India’.
Q5. Write a method in Python to count the number
of vowels in a text file
Binary files in Python
 A binary file is used to store data in binary format.
 We can open some binary files in the normal text editor but we
an’t read the content present inside the file.
 That’s because all the binary files will be encoded in the binary
format, which can be understood only by a computer
Since they are directly in the form of binary hence there is no
need to translate them.
 It contains arbitrary data, usually numbers stored in the file,
which can be used fro numerical operations.

 It is used to store binary data such as images, videos audio etc.


 That’s why these files are easy and fast in working.
 In binary files, there is no delimiter to end a line.
DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES
Text Files Binary Files
1. Text Files are sequential 1. A Binary file contain arbitrary
files binary data
2. Text files only stores texts 2 Binary Files are used to store
binary data such as image, video,
audio, text
3. There is a delimiter EOL 3. There is no delimiter
(End of Line i.e \n)

4. Text files easy to understand 4. Binary files are difficult to


because these files are in understand.
human readable form
5. Text files are having extension 5. Binary files are having .dat
.txt extension
File Access Modes in Binary Files
Mode Description
rb Read Only in binary format.

rb+ To Read and write binary file. But the file pointer will be at the
beginning of the file.

wb Binary file only in writing mode, if file is existing the old file will be
overwritten else the new file will be created.

wb+ Binary file only in reading and writing mode, if file is existing the old file
will be overwritten else the new file will be created.

ab Append mode in binary file. The file pointer will be at the end of the file.

Appending and reading in binary file if the file is existing then file
ab+
pointer will be at the end of the file else new file will be created for
reading and writing.
Opening & Closing a Binary file
Open() function is used to open a binary file same as text file. The
only difference is the mode which it is opened.
For Exp. F= open (“Binaryfile. dat”,”rb”)
A part from using open() function for creation of file , with
statement can also be used.
For Exp. With open(“ Binary.dat”,”r+”) as f
Closing Binary file : After performing desired operations on file,
we need to close it. This can be done same as text file using
close() function.
For Exp. F. close()

Important Note :-
In Python, files are opening in Text mode by default and so to open files in binary
mode , when specifying a mode, add ‘b‘ to it. For Example, read mode will
became ‘rb’, write mode will became ‘wb’ , append mode will became ‘ab’, and
read write will became ‘ab+’
BASIC OPERATIONS ON BINARY FILE
Basic operations performed on a Binary file are:
Write a record in a binary file

Read records from a binary file

Search record from a binary file

Update a record in a binary file

Append a record in a binary file


Pickling and Unpickling in Python
“Python pickle module is used for serializing and de-serializing python
object structures. The process to converts any kind of python objects
(list, dict, etc.) into byte streams (0s and 1s) is called Pickling , It is also called
serialization or flattening or marshalling. “Unpickling” is the reverse of this
where by a byte stream is converted into an object. which can be read by
the user. Pickle.dump()
Pickle module provides two main methods :
dump()function is used to serialize the object, like list, Pickle.load()
dictionary etc into byte stream.( Write the object to a file)
Load() is used to desterilize the files data back to the python object. (Read the file)

Important Note :-
• Pickle is a built – in module in Python.
• It is used write of read a structure such as list or dictionary to a file.
• First we need to import the Pickle module.
import pickle
Working of Pickling(dump())
• It writes the object to a
Structure (List /
file.
Dictionary)
Code • Syntax:

pickle.dump(object,FileObject)
• Object can be list,
Pickling dictionary or number.
• FileObject is the file
handler

Byte Output
Stream
m

le
e adab
R
Writing to Not
File
Working of Unpickling( load())
• As we know that binary files
are not in readable form Byte
• pickle.load() is used to read Stream
from binary file.
• Syntax:
object=pickle.load(FileObject)
• Object can be list, dictionary Unpickling
or number. Output
• FileObject is the file handler

Structure (List /
Code
Dictionary)

User Readable

Note : pickle.load() read only one record at a time.


Daily Quiz & MCQ
A. Fill in the Blanks :
1) Three main types of data files are __ , and ___________
2) _file stores the data in ASCII format.
3) _ _module is used for writing/ reading data in/from binary files.
4) function is used to read object from binary file.
5) Pickle.dump() is used to the object.
B. MCQ:
1) Pickling means:
a) converting the structure to a byte stream
b) converting the byte stream back to the original structure
c) Both a & b
d) None of the these.
2. Which file is directly readable: 3. Pickle is :
a) Text File a) User define module
b) Binary File b) Built in function
c) Both c) Built in module
d) Noe of These d) None of these
.
Expected Questions for Board Exam
1. What is a data file?
2. Differentiate between Text and Binary files.
3. What is the use of pickle module in python?
4. Differentiate between pickling and unpickling.
5. Write a python program to write multiple numbers in a binary
file named “number.dat”.
6. Write a python program to write a dictionary structure in
binary file and read it back in same program.
7. WAP to read an object from binary file.
8. Differentiate between read(),readline()and readlines() functions
9. How is write() different from writelines() ?
10. Explain the difference between write and append mode of opening
a file.
Significance of File Pointer in
File Handling
• File pointers which tells the current position in the file where
reading or writing takes place.
• File modes and Opening Position of File - Pointer:
File Modes Opening position of file pointer

r,rb,r+,rb+,r+b Beginning of the file.

w,wb,w+,wb+, w+b Beginning of the file.

a,ab,a+,ab+,a+b At the end of the file, if the file exists


otherwise creates a new file.
RANDOM ACCESS METHODS
All reading and writing functions discussed till now, work sequentially in the file.
To access the contents of file randomly .
Following methods are use.

seek method
tell method
seek() function is used to change the position of the file handle (file
pointer) to a given specific position. File pointer is like a cursor, which defines
from where the data has to be read or written in the file.
Syntax :
f.seek(offset, from_what)
 where f is file pointer
 seek(offset) : Change the cursor position by bytes as specified by the offset.
 Offset is added to from_what (reference point) : To get the position.
seek() & tell() Methods
The reference point is defined by the "from_what"
argument. It can have any of the three values:
0: sets the reference point at the beginning of the file,
which is by default.
1: sets the reference point at the current file position.
2: sets the reference point at the end of the file.
Important Point :-
In Python 3.X and above we can Seek from beginning only, if
opened in text mode. We can overcome from this by opening the
file ion b mode.
tell() method returns an integer giving the current position of
object in the file. The integer returned specifies the number of bytes
from the beginning of the file till the current position of file object.
It's syntax is : fileobject.tell()
Examples on seek() & tell()
Output
HANDLING FILES THROUGH OS MODULE
OS module provides many such functions which can
be used to work with files and directories. OS means
Operating System.The os module of Python allows
you to perform Operating System dependent
operations such as making a folder, listing contents
of a folder, know about a process, end a process
rename a file , remove a file etc…
Let's see some useful os module methods that can
help you to handle files and folders in your program.
• First we need to import the os module.
METHODS OF OS MODULE
S.NO Function Syntax Use
Name
01 os.mkdir(“newdir”) To create directory in the current
mkdir() directory.
02 os.chdir(“newdir”) To change the current directory
chdir()
03 os.getcwd() It display the current directory
getcwd()
04 os.rmdir(“newdir”) To delete the directory
rmdir()
05 Os.rename(cur_file, It is used to rename the file.
rename() new_File)
06 os.remove(File_name) It is used to delete the file.
remove()

07 listdir() os.listdir() It display list of files in the current


directory
08 path.isfile() os.pathisfile(“File Name”) If the file exist it return True otherwise
false
Absolute Path and Relative Path
• We all know that the files are kept in directory
which are also known as folders.
• Every running program has a current directory.
Which is generally a default directory and python
always see the default directory first.
• getcwd( ) is a very function which can be used to
identify the current working directory.
• There are two types of Path
1. Absolute path
2. Relative path
ABSOLUTE PATH
An absolute path is a path that starts right from the root of
your computer file system. In Windows, that means the
inclusion of the drive letter (like C:). A path is also called
pathname

ABSOLTE PATH
RELATIVE PATH
A relative path, is a path starting from the Current Directory of your
program. The Current Directory is usually the directory containing the
file executed.
For Example :-
If my current working directory is c:\program, then to access .py, we
should write only append.py.

Programs\append.py

RELATIVE PATH
Standard Input, Output and Error Stream
• Standard Input Device(stdin)- reads from the keyboard
• Standard Output Device(stdout)- prints to the display and can
be redirected as standard input.
• Standard Error Device(stderr)- same as stdout but normally
only for errors.
• The above devices are implemented as files in Python , called
standard streams.
• We can use these stream files by using sys modules.
• Import sys module.
• sys.stdin.read() : let you read from keyboard.
• sys.stdout.write() : let you write on the standard output device, the
monitor.
• sys.stdin is the file for input, always opens in read mode.
• sys.stdout is the file for output , always opens in write mode
Standard File Streams
• We use standard I/O Streams to get better performance
from different I/O devices.
• Some Standard Streams in python are as follows -
– Standard input Stream sys.stdin
– Standard output Stream sys.stdout
Output
– Standard error Stream
sys.stderr
Daily Quiz & MCQ
#Write a program to write and read multiple record in the form of list in a

binary file according to the user choice

Algoritham
Opens a binary file “Employee.dat” in
write mode and then write these list
to a binary file using dump
method,according to the user want.
The load method is used to read the
object from the binary file.
Note: The pickle.load() function
raises EOFError(a run time exception
error) when the end of file is reached
while reading from the file. This can
be handled either by using try and
except block
#Write a program to append and display multiple record in the form of
list
in a binary file according to the user choice To add more data
at the end of the
file the file is
opened in an
append mode.
Algoritham
Opens a binary file
“Employee.dat” in append
mode and then write these
list to a binary file using
dump method,according to
the user want. The load
method is used to read the
object from the binary file.
Note: The pickle.load()
function raises EOFError(a
run time exception error)
when the end of file is
reached while reading from
the file. This can be handled
either by using try and
except block
# W.A.P to Searching records according to the Emp_no
Algoritham
Step-1 open the file in binary in read mode
Step-2 Input the Emp_no whose data needs to be searched.
Step-3 Apply loop to read the file record by record from beginning till end.
Step-4 Read the record of the file in a list using load method
Step-5 If the Employee no. read from the file matches the Emo_no to be searched then print the
record and display the message “Found”.
Step-6 If the Employee number read from the file does not match the Emp_no to be searched
then the variable found remains false and "Record not found" is displayed.
Step-7 Close the file

Note:
The pickle.load()
function raises
EOFError(a run time
exception error)
when the end of file
is reached.
# W.A.P to updating the salary you want in Multiple records
Algoritham
Step-1 opening the file in both
reading and writing modes.
Step 2 Input the Employee No. whose
data needs to be modified.
Strp-3 Apply loop to read the file
record by record from
beginning till end.
Step-4 Store the position of file
pointer of the beginning of
the record
Step-5 Read the record of the file in a
list
Step- 6 Asdk the user to enter the
modified salary
Step-7 Overwrite the earlier record
with new record
Step8 Write the modified record
back to the file
Step-9 If the Employee number read
from the file does not match
the Emp_no to be searched
then the variable found
remains false and "Record
not found" is displayed
Step-10 Close the file
#WAP to delete data in Binary file
import pickle
import os
def delete_rec():
f=open("Student.dat","rb")
f1=open("Temp.dat","wb")
a=int(input(" Enter the Roll no to be deleted"))
found=0
try:
while True:
R=pickle.load(f)
if R[0]==a:
found+=1
else:
pickle.dump(R,f1)
except EOFError:
f.close()
f1.close()
if found==0:
print("Record not found")
os.remove("Student.dat")
os.rename("Temp.dat","Student.dat")

delete_rec():
Practical Questions
which can be asked
in the Board
Examination.
(Binary file)
Expected Board Questions Binary file ( 3Marks)
Q1. Write a function definition to search and display all those records of
the student whose percentage is between 70 and 90 (Both inclusive)
Assuming that the data is stored in the Binary file in the following
format:
[[1,’Ram’, ‘A’, 75], [2,’Allen’, ‘B’, 75], [2,’Neha’, ‘C’, 75],……..] and so on

Q2 Write a function definition to display the names of all those students


who secured Grade ‘A’

Q3. Write a function defination to transfer all the records from binary file
“Pro” to “Newpro” whose price is less than 1000.

Q4. Write a function defination to write a new binary file called


“Data”.Dat” which stores name and price of the product in the format
shown in the example
Assuming that the data is stored in the Binary file in the following
format:
[{‘name’:’File’,Price:100}, {‘name’:’Pen’,Price:10},
{‘name’:’Book’,Price:300},……..] and so on
What are CSV file ?????
 CSV is a file it stands for Comma separated values , it is a
simple file format used to store tabular data, such as
spreadsheet or database. In which each line is a record. The
record consist of fields separated by comma.

 It can be Notepad file, in which each row data should be


separated by comma., When you will open in Notepad it will
display normal text separated by comma.

 It can be opened in Ms Excel ,it will display in tabular form and it


is easy to manipulate the data.

 The separator character of csv file is called as delimiter. Default


delimiter is comma (,). Other delimiters are tab (‘\t’),colon
(:), pipe (|) and semicolon ( ; ) character .
Benifits of using CSV file
 CSV files stored data in form of a spreadsheet or database
It organizes data effectively.
It is very easy to import data from excel.
CSV files are of plain text format hence, it makes easy for website
development to use that data.
 They also plain text files having ASCII/Unicode character
Used to handle large amount of data.
Language which support text files will also support CSV files.
Data is stored in the form of row and column/tabular form. Thus
easy to except from databases or spreadsheets
 CSV files can be easily imported to other program.
Easily open the file in spreadsheet and databases.
CSV modules
CSV Module provides two types of Objects:

(i) Reader : to read from the CSV files.

(ii) Writer : to write in the CSV files.


Note:-
 To import CSV module in our program,
write the following statement
import csv
 The file extension of csv file .csv
Opening & Closing CSV File
Open a CSV file: Open() function is used to
open a CSV file same as text file.
For Example:-
f=open(“student.csv”,”r”)
OR
with open(“student.csv”, “w”) as f
 Close a CSV file:This can be done same as
text file using close() function.
For Example:-
f.close()
Writing in CSV files
Function Name Use
csv.writer(“File object”) Returns a writer object
which write data into
CSV file.
<writer object>.writerow(“File name”) Write one row of data
on to their writer
object.
<writer object>.writerows(“File name”) Write multiple rows of
data on to their writer
object.

NOTE :- The CSV .writer() function returns a writer object


that converts the user’s data into a delimited string. This
string can later be used to write into CSV files using the
Writing in a csv file using writerow()
Open with Notepad

Open with msExcel


Reading from csv file
 To read data from a CSV file , reader
function of CSV module is used.
 csv.reader() function is used to read
the records from the CSV file.
 The records read are in the form of list
of list.
 Records can also be read into dictionary
using csv.dictreader () function.
How to read data from a CSV file

Output
How to Search data from a csv file

Output
Practical Questions
which can be asked
in the Board
Examination.
(CSV File)
Expected Board Questions CSV file ( 3Marks)
Q1. Write a user define function search() to display those
percentage are in the range of 80 and 90 (both values
included)
Q2. Write a python script to create a file Camera.CSV having
fields ModelNO,Megapixel, Zoom and details using tab as a
delimiter.
Q3. Write a python script to read a Voter.CSV file having fields
Voter_ID,VoterName,VoterAge.Display those records where
voter age is more than 65.
Q4. Write a python script to read a Student.CSV file having
fields RollNo,Eng,Science,Math,SST marks. Calculate total and
pecentage. Display Rollno,total and percentage of all students.
Q5.Write a Python script to read a PHONE.CSV file containing
Name, Address, Areacode and phone no. Display all records in
ascending order.

You might also like