Prepared By:
Pradeep Vithule
PGT CS
INTRODUCTION TO
PYTHON
Data File
• File handling: Need for a data file, Types of file: Text files, Binary files
and CSV (Comma separated values) files.
• Text File: Basic operations on a text file: Open (filename – absolute or
relative path, mode) / Close a text file, Reading and Manipulation of
data from a text file, Appending data into a text file, standard input /
output and error streams, relative and absolute paths.
• Binary File: Basic operations on a binary file: Open (filename –absolute or
relative path, mode) / Close a binary file, Pickle Module – methods load
and dump; Read, Write/Create, Search, Append and Update operations in
a binary file.
• CSV File: Import csv module, functions – Open / Close a csv file, Read
from a csv file and Write into a csv file using csv.reader ( ) and csv.
writerow( ).
Contents
File
File is a bunch of bytes stored on some storage devices on lower level file is
interpreted as sequence or steams of bytes.
Stream
Stream is a sequence of bytes. It represents flow of data at lower level.
FILE
• User provides data in form of input to program from
console input (keyboard) and it is not saved. In the same
way, output is displayed on console
output (visual display) but it is not saved anywhere.
• If program has to be executed again, user needs to enter all
data again.
• It is not a big deal for small set of input but for large data
it is
very difficult to enter input again.
• The data entered in one program or output produce from one
program may be required for some other program.
• Data needs to be stored on files.
NEED FOR A DATA FILE
TYPES OF FILE
Data file can be stored in two ways:
• Text file: File made up of only ASCII
characters
• Easy to read strings from plain text files
• Most operating systems come with basic tools to
view and edit them
• Text files good choice for simple information
• Easy to edit
• Cross-platform
• Human readable!
TYPES OF FILE
• Binary file: data is stored in same format as it is held
in memory, so interpreting the correct data type while
reading the file is very important.
• It can be used to store complex data structures like
list and dictionary.
• CSV stands for Comma Separated Values
• CSV file is a type of plain text file means data stored in form of ASCII
or Unicode characters
• Each line is a row and in row each piece of data is separated by a comma
• It is common format for data interchange
• CSV file example:-
Roll No., Name,
Marks
1,Vinit,30
2,Alka,26
3,Rohit,28
CSV FILE
FILE
• File processing takes place in the following order.
• Open a file that returns a filehandle.
• Use the handle to perform read or write action.
• Close the filehandle.
BASIC OPERATIONS ON A TEXT
OPEN A FILE
OPEN A FILE
• Python’s built-in open() function
−It is used to open a file and return a file object .
−File objects contain methods and attributes about the file
− open() is most commonly used with two arguments
−Syntax:- file_object_name = open(filename,
mode)
• The first argument is the filename
– Example :- f=open("ana.txt")
– file extension is .txt
– Python looks in the current directory for the file
FILE ACCESS MODES
• The second argument is the file access mode
• Open file by using with statement
• Syntax:-
with open(“aarohi.txt”, “r”) as f:
• With statement ensure all resources allocated to
file object gets deallocated automatically once we
stop using file.
• there is no need to call file.close()
OPEN A FILE
Python can access a file in any directory by providing the proper
path
•Absolute path contains the full path to the file and not only the file.
It always starts at the same place, which is the root directory. For
Example
"C:UsersitpDesktopwords.txt"
• Relative path describes the location of a file or folder in relative to
the current working directory. For example
"datawords.txt"
ABSOLUTE OR RELATIVE
PATH
Use the close() method to close a text file
fin.close()
• Whenever you are done with a file, it is good programming
practice to close it
•It will release the resources allocated to file
CLOSE A FILE
• Reading a character by using read() funtion
• Use the read(n) function to read the next n
number of characters
• Python remembers where it last read, and each subsequent
read(n) begins where the last ended
• To start back at the beginning of a file, close and open it
• If you don't specify a number, Python returns the entire
file as a string
– Only good for small files
READING FROM FILE
EXAMPLE 1:- character wise analysis
Write a function to count a specific character
EXAMPLE
def count_specific():
f=open("aarohi.txt",'r')
c=0
a=f.read()
for i in a:
if i=='s':
c=c+1
print("No of s in file=",c)
f.close()
count_specific()
# defining a function
# open file in read
# variable to count
# read all content and store in string
# iterate through all character one by one
# condition
# increment /display
#close the file
# call the function to perform the task
EXAMPLE 2:- word wise
analysis Write a function to count
a word
EXAMPLE
def count_the():
f=open("aarohi.txt",'r')
c=0
a=f.read()
b=a.split()
for i in b:
if i.lower()=="the":
c=c+1
print("No of The word =",c)
f.close()
# read all content and store in string
# split the string into words
# iterate through all words one by one
# condition
# increment /display
#close the file
• Use the readline(n) method where n is the number
of characters you want to read from the current
line
• The method returns the characters as a string
• Once you read all of the characters of a line,
the
next line becomes the current line
• If you don't pass a number, the method returns the
entire line
• readline() reads characters from the current line
READING CHARACTERS FROM A LINE
• Reading all lines into a list
– Use the readlines() method to read a text file
into a list where each line of the file
becomes a string element in the list
• difference between readline() and readlines()
- readline() read character from one line and
readlines() read all line
- readline() return string and readlines() return list of
string
LINES
EXAMPLE 1:- line wise analysis
Write a function to display line starting with m
EXAMPLE
def display():
f=open("aarohi.txt",'r')
c=0
a=f.readlines()
for i in a:
if i[0]=="m":
print(i)
f.close()
# read all content line by line in list of
string
# iterate through all line one by one
# condition
# increment /display
#close the file
• Writing strings to a text file
– Use the write(string) method which writes a
string to a text file
– write() does not automatically insert a newline
character at the end of a string
– You have to put newlines in where you want
them (use n)
• Writing a list of string to a text file
– Use the writelines(list) method
2 WAYS OF WRITING TO A TEXT FILE
EXAMPLE 1:- Write in a file
Write a program to write lines in file using writeline function
EXAMPLE
def write_fun():
f=open("text2.txt",'w')
l=[]
while True:
s=raw_input("Enter
line to be enter")
l.append(s)
if raw_input("Enter E if want to
exit")=="E": break
f.writelines(l)
f.close()
write_fun()
# open file in write mode
# read line from keyboard
# append lines in list
# write list of string in file
EXAMPLE 2:- appending data in file
Write a program to append lines in file using write function
EXAMPLE
def write_fun():
f=open("text.txt",'a')
while True:
s=input("Enter line to be enter")
f.write(s)
f.write("n")
if input("Enter E if want to
exit")=="E": break
f.close()
write_fun()
# open file in append mode
# read line from keyboard
# write line in file
# write next line character
FILE METHODS SUMMARY
ERROR STREAMS
The standard devices are treated as file and often referred to as
“streams”.
• Standard input (stdin) read data from keyword
• Standard output (stdout) make output on monitor
• Standard error (stderr) output error on monitor
• In python sys module help to use these standard stream
• Example:-
import sys
a=sys.stdin.read(5)
sys.stdout.write(“hi”)
STANDARD INPUT / OUTPUT AND
EXAMPLE 1:- Use of standard stream
Write a program to check whether a number is prime or
not.
EXAMPLE
import sys
sys.stdout.write("enter number to be checked")
a=int(sys.stdin.read(2))
for i in range(2,a):
if a%i==0:
sys.stdout.write("not a
prime")
break
else:
sys.stderr.write("prime")
# output on screen
# read from keyboard
# output on screen
# output in red color
FILE
•binary file is also opened and closed in same way as text file by open() function
and close() function respectively but extension of file is .dat and mode of
opening binary file is given below:
Syntax:- file_object=open('data.dat', 'wb')
BASIC OPERATIONS ON A BINARY
• pickle module can be used to store any kind of object in file as
it allows us to store python objects with their structure. pickle
module converts Python object into a series of bytes. The byte
stream representing the object can be transmitted or stored,
and reconstructed to create a new object with the same
characteristics.
• “Pickling” is the process whereby a Python object is converted
into a byte stream
• “unpickling” is the process whereby a byte stream (from
a binary file) is converted back into an object
PICKLE
• Function in pickle module
• load()- Read and return an object from the pickle data stored
in a file
• dump()- Write a pickled representation of obj to the
open file
object file
PICKLE
EXAMPLE 1:-
Read from binary file containing list of dictionary (d={“Name”:”ana”,
“Class”:12})
READ FROM A BINARY FILE
import pickle
f=open("xyz.dat",'rb')
x=pickle.load(f)
for i in x:
print(i)
f.close()
# pickle is used for binary
file
# read data from binary file
# iterate through element in
x
#process each element
EXAMPLE 1:-
Search from binary file containing list of dictionary (d={“Name”:”ana”,
“Class”:12})
SEARCH FROM A BINARY FILE
import pickle
f=open("xyz.dat",'rb')
x=pickle.load(f)
for i in x:
if i["Class"]==11:
print(i)
f.close()
# pickle is used for binary
file
# read data from binary file
# iterate through element in
x
# check condition
EXAMPLE 1:- Write in binary file a list of dictionary
import pickle
f=open("xyz.dat",'wb')
l=[]
while True:
d={"Name":input("
Enter Your Name"),
"Class":int(input("e
nter your class"))}
l.append(d)
if input("Enter E for
Exit")=="E": break
pickle.dump(l,f)
f.close()
WRITE TO A BINARY FILE
• Data can be appended into end of the file by opening file in
‘ab’ mode
• dump function is used to write new data in same way
• load function need to be used for each set of data that are
separately dumped in same file.
• For example you dumped data two times in file then you need
to load two time to view all data in file.
APPEND INTO BINARY FILE
EXAMPLE 1:- append data in binary file a list of dictionary
import pickle
f=open("xyz.dat",‘ab')
l=[]
while True:
d={"Name":input("
Enter Your
Name"),
"Class":int(input("
enter your class"))}
l.append(d)
if input("Enter E for
Exit")=="E": break
pickle.dump(l,f)
f.close()
APPEND INTO BINARY FILE
AFTER APPENDING DATA
EXAMPLE 1:-
Read from binary file containing list of
dictionary (d={“Name”:”ana”, “Class”:12}) that dumped more than
one time.
READ FROM A BINARY
FILE
import pickle
f=open("xyz.dat",'rb')
while True:
try:
x=p
ickl
e.l
oa
d(f)
print(x)
except
# pickle is used for binary
file
# work again and again
# check if load will raise error
#load one set of data that dumped
together
# if reached EOF then load will raise error that is handled
by try and break is executed to send control out of loop
# close file
Seek() Method
• The seek(offset[, from]) method changes the current file position
• Take two parameter :-
seek(offset, whence=SEEK_SET)
• Change the stream position to the given byte offset.
• Offset is interpreted relative to the position indicated by whence. Values for
are:
-SEEK_SET or 0 – start of the stream (the default); offset
should be zero or positive
-SEEK_CUR or 1 – current stream position; offset can be +ve
zero or –ve
-SEEK_END or 2 – end of the stream; offset is
usually negative but can +ve zero or –ve
whence
+ve offset means forward
-ve offset means backward
0 means to that position
FILE POSITIONS:-
Tell() Method
• The method tell() returns the current position of
the read/write pointer within the file
fileObject.tell()
• Not take any parameter
FILE POSITIONS
EXAMPLE 1:-
Update data binary file containing list of dictionary (d={“Name”:”ana”,
“Class”:12}).
UPDATE BINARY FILE
import pickle
f=open("abc.dat",'rb+')
x=pickle.load(f)
for i in x:
if
i['Name']=='a
yesha':
i['Class']=12
print("updated")
f.seek(0)
pickle.dump(x,f)
# pickle is used for binary
file
# read data
# iterate through all
data
#check condition
#modify data
# send file pointer to beginning of
file
# write modified data into file
# close file
• csv module provides classes that assist in the reading and
writing of Comma Separated Value (CSV) files
• Statement to import csv module:-
import csv
• To open a csv file, use open() function as used previously in
text and binary file.
• Syntax:-
•
• To close a csv file, use close() function as used previously in
text and binary file.
• Syntax:- file_object.close()
file_object=open(‘filename.csv', ‘mode')
f=open('data.csv', 'w')
CSV MODULE
• csv.reader :- It is a built-in function in module csv. It take
file object as an argument and The returned object is an
iterator. Each iteration returns a row of the CSV file
• Syntax:- csv_reader = csv.reader( file_object)
• csv.writer:-It is a built-in function in module csv. It take file
object and returns a writer object responsible for converting
the user’s data into delimited strings. Writer object have public
methods which are used to write content in csv file like
writerow()
• Syntax :-
•
wrt=csv.writer(file_object)
wrt.writerow(d1,d2,d3)
FUNCTION IN CSV MODULE
EXAMPLE 1:-
Write a program to read data from csv file and display it.
READ FROM CSV FILE
import csv
f=open('ar.csv', 'r')
f_reader =
csv.reader(f) for row in
f_reader:
print (row)
f.close()
# to use csv file
# open csv file in read mode
# read data from csv file in form of rows
# iterate through all data
# process data
#close file
EXAMPLE 1:-
Write a program to read data from csv file and display it.
WRITE DATA INTO CSV FILE
import csv
f=open('data1.csv',
'w') wrt=csv.writer(f)
d={}
while True:
name=input("enter your name")
age=int(input("enter your age"))
class_sec=input("enter your class")
wrt.writerow([name, age,
class_sec]) if input("Enter E for
Exit")=="E":
break
#open csv file in write mode
# create a writer object
#input data
#Write one row in
file
THANK YOU

01 file handling for class use class pptx

  • 1.
    Prepared By: Pradeep Vithule PGTCS INTRODUCTION TO PYTHON
  • 2.
    Data File • Filehandling: Need for a data file, Types of file: Text files, Binary files and CSV (Comma separated values) files. • Text File: Basic operations on a text file: Open (filename – absolute or relative path, mode) / Close a text file, Reading and Manipulation of data from a text file, Appending data into a text file, standard input / output and error streams, relative and absolute paths. • Binary File: Basic operations on a binary file: Open (filename –absolute or relative path, mode) / Close a binary file, Pickle Module – methods load and dump; Read, Write/Create, Search, Append and Update operations in a binary file. • CSV File: Import csv module, functions – Open / Close a csv file, Read from a csv file and Write into a csv file using csv.reader ( ) and csv. writerow( ). Contents
  • 3.
    File File is abunch of bytes stored on some storage devices on lower level file is interpreted as sequence or steams of bytes. Stream Stream is a sequence of bytes. It represents flow of data at lower level. FILE
  • 4.
    • User providesdata in form of input to program from console input (keyboard) and it is not saved. In the same way, output is displayed on console output (visual display) but it is not saved anywhere. • If program has to be executed again, user needs to enter all data again. • It is not a big deal for small set of input but for large data it is very difficult to enter input again. • The data entered in one program or output produce from one program may be required for some other program. • Data needs to be stored on files. NEED FOR A DATA FILE
  • 5.
    TYPES OF FILE Datafile can be stored in two ways: • Text file: File made up of only ASCII characters • Easy to read strings from plain text files • Most operating systems come with basic tools to view and edit them • Text files good choice for simple information • Easy to edit • Cross-platform • Human readable!
  • 6.
    TYPES OF FILE •Binary file: data is stored in same format as it is held in memory, so interpreting the correct data type while reading the file is very important. • It can be used to store complex data structures like list and dictionary.
  • 7.
    • CSV standsfor Comma Separated Values • CSV file is a type of plain text file means data stored in form of ASCII or Unicode characters • Each line is a row and in row each piece of data is separated by a comma • It is common format for data interchange • CSV file example:- Roll No., Name, Marks 1,Vinit,30 2,Alka,26 3,Rohit,28 CSV FILE
  • 8.
    FILE • File processingtakes place in the following order. • Open a file that returns a filehandle. • Use the handle to perform read or write action. • Close the filehandle. BASIC OPERATIONS ON A TEXT
  • 9.
    OPEN A FILE OPENA FILE • Python’s built-in open() function −It is used to open a file and return a file object . −File objects contain methods and attributes about the file − open() is most commonly used with two arguments −Syntax:- file_object_name = open(filename, mode) • The first argument is the filename – Example :- f=open("ana.txt") – file extension is .txt – Python looks in the current directory for the file
  • 10.
    FILE ACCESS MODES •The second argument is the file access mode
  • 11.
    • Open fileby using with statement • Syntax:- with open(“aarohi.txt”, “r”) as f: • With statement ensure all resources allocated to file object gets deallocated automatically once we stop using file. • there is no need to call file.close() OPEN A FILE
  • 12.
    Python can accessa file in any directory by providing the proper path •Absolute path contains the full path to the file and not only the file. It always starts at the same place, which is the root directory. For Example "C:UsersitpDesktopwords.txt" • Relative path describes the location of a file or folder in relative to the current working directory. For example "datawords.txt" ABSOLUTE OR RELATIVE PATH
  • 13.
    Use the close()method to close a text file fin.close() • Whenever you are done with a file, it is good programming practice to close it •It will release the resources allocated to file CLOSE A FILE
  • 14.
    • Reading acharacter by using read() funtion • Use the read(n) function to read the next n number of characters • Python remembers where it last read, and each subsequent read(n) begins where the last ended • To start back at the beginning of a file, close and open it • If you don't specify a number, Python returns the entire file as a string – Only good for small files READING FROM FILE
  • 15.
    EXAMPLE 1:- characterwise analysis Write a function to count a specific character EXAMPLE def count_specific(): f=open("aarohi.txt",'r') c=0 a=f.read() for i in a: if i=='s': c=c+1 print("No of s in file=",c) f.close() count_specific() # defining a function # open file in read # variable to count # read all content and store in string # iterate through all character one by one # condition # increment /display #close the file # call the function to perform the task
  • 16.
    EXAMPLE 2:- wordwise analysis Write a function to count a word EXAMPLE def count_the(): f=open("aarohi.txt",'r') c=0 a=f.read() b=a.split() for i in b: if i.lower()=="the": c=c+1 print("No of The word =",c) f.close() # read all content and store in string # split the string into words # iterate through all words one by one # condition # increment /display #close the file
  • 17.
    • Use thereadline(n) method where n is the number of characters you want to read from the current line • The method returns the characters as a string • Once you read all of the characters of a line, the next line becomes the current line • If you don't pass a number, the method returns the entire line • readline() reads characters from the current line READING CHARACTERS FROM A LINE
  • 18.
    • Reading alllines into a list – Use the readlines() method to read a text file into a list where each line of the file becomes a string element in the list • difference between readline() and readlines() - readline() read character from one line and readlines() read all line - readline() return string and readlines() return list of string LINES
  • 19.
    EXAMPLE 1:- linewise analysis Write a function to display line starting with m EXAMPLE def display(): f=open("aarohi.txt",'r') c=0 a=f.readlines() for i in a: if i[0]=="m": print(i) f.close() # read all content line by line in list of string # iterate through all line one by one # condition # increment /display #close the file
  • 20.
    • Writing stringsto a text file – Use the write(string) method which writes a string to a text file – write() does not automatically insert a newline character at the end of a string – You have to put newlines in where you want them (use n) • Writing a list of string to a text file – Use the writelines(list) method 2 WAYS OF WRITING TO A TEXT FILE
  • 21.
    EXAMPLE 1:- Writein a file Write a program to write lines in file using writeline function EXAMPLE def write_fun(): f=open("text2.txt",'w') l=[] while True: s=raw_input("Enter line to be enter") l.append(s) if raw_input("Enter E if want to exit")=="E": break f.writelines(l) f.close() write_fun() # open file in write mode # read line from keyboard # append lines in list # write list of string in file
  • 22.
    EXAMPLE 2:- appendingdata in file Write a program to append lines in file using write function EXAMPLE def write_fun(): f=open("text.txt",'a') while True: s=input("Enter line to be enter") f.write(s) f.write("n") if input("Enter E if want to exit")=="E": break f.close() write_fun() # open file in append mode # read line from keyboard # write line in file # write next line character
  • 23.
  • 24.
    ERROR STREAMS The standarddevices are treated as file and often referred to as “streams”. • Standard input (stdin) read data from keyword • Standard output (stdout) make output on monitor • Standard error (stderr) output error on monitor • In python sys module help to use these standard stream • Example:- import sys a=sys.stdin.read(5) sys.stdout.write(“hi”) STANDARD INPUT / OUTPUT AND
  • 25.
    EXAMPLE 1:- Useof standard stream Write a program to check whether a number is prime or not. EXAMPLE import sys sys.stdout.write("enter number to be checked") a=int(sys.stdin.read(2)) for i in range(2,a): if a%i==0: sys.stdout.write("not a prime") break else: sys.stderr.write("prime") # output on screen # read from keyboard # output on screen # output in red color
  • 26.
    FILE •binary file isalso opened and closed in same way as text file by open() function and close() function respectively but extension of file is .dat and mode of opening binary file is given below: Syntax:- file_object=open('data.dat', 'wb') BASIC OPERATIONS ON A BINARY
  • 27.
    • pickle modulecan be used to store any kind of object in file as it allows us to store python objects with their structure. pickle module converts Python object into a series of bytes. The byte stream representing the object can be transmitted or stored, and reconstructed to create a new object with the same characteristics. • “Pickling” is the process whereby a Python object is converted into a byte stream • “unpickling” is the process whereby a byte stream (from a binary file) is converted back into an object PICKLE
  • 28.
    • Function inpickle module • load()- Read and return an object from the pickle data stored in a file • dump()- Write a pickled representation of obj to the open file object file PICKLE
  • 29.
    EXAMPLE 1:- Read frombinary file containing list of dictionary (d={“Name”:”ana”, “Class”:12}) READ FROM A BINARY FILE import pickle f=open("xyz.dat",'rb') x=pickle.load(f) for i in x: print(i) f.close() # pickle is used for binary file # read data from binary file # iterate through element in x #process each element
  • 30.
    EXAMPLE 1:- Search frombinary file containing list of dictionary (d={“Name”:”ana”, “Class”:12}) SEARCH FROM A BINARY FILE import pickle f=open("xyz.dat",'rb') x=pickle.load(f) for i in x: if i["Class"]==11: print(i) f.close() # pickle is used for binary file # read data from binary file # iterate through element in x # check condition
  • 31.
    EXAMPLE 1:- Writein binary file a list of dictionary import pickle f=open("xyz.dat",'wb') l=[] while True: d={"Name":input(" Enter Your Name"), "Class":int(input("e nter your class"))} l.append(d) if input("Enter E for Exit")=="E": break pickle.dump(l,f) f.close() WRITE TO A BINARY FILE
  • 32.
    • Data canbe appended into end of the file by opening file in ‘ab’ mode • dump function is used to write new data in same way • load function need to be used for each set of data that are separately dumped in same file. • For example you dumped data two times in file then you need to load two time to view all data in file. APPEND INTO BINARY FILE
  • 33.
    EXAMPLE 1:- appenddata in binary file a list of dictionary import pickle f=open("xyz.dat",‘ab') l=[] while True: d={"Name":input(" Enter Your Name"), "Class":int(input(" enter your class"))} l.append(d) if input("Enter E for Exit")=="E": break pickle.dump(l,f) f.close() APPEND INTO BINARY FILE
  • 34.
    AFTER APPENDING DATA EXAMPLE1:- Read from binary file containing list of dictionary (d={“Name”:”ana”, “Class”:12}) that dumped more than one time. READ FROM A BINARY FILE import pickle f=open("xyz.dat",'rb') while True: try: x=p ickl e.l oa d(f) print(x) except # pickle is used for binary file # work again and again # check if load will raise error #load one set of data that dumped together # if reached EOF then load will raise error that is handled by try and break is executed to send control out of loop # close file
  • 35.
    Seek() Method • Theseek(offset[, from]) method changes the current file position • Take two parameter :- seek(offset, whence=SEEK_SET) • Change the stream position to the given byte offset. • Offset is interpreted relative to the position indicated by whence. Values for are: -SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive -SEEK_CUR or 1 – current stream position; offset can be +ve zero or –ve -SEEK_END or 2 – end of the stream; offset is usually negative but can +ve zero or –ve whence +ve offset means forward -ve offset means backward 0 means to that position FILE POSITIONS:-
  • 36.
    Tell() Method • Themethod tell() returns the current position of the read/write pointer within the file fileObject.tell() • Not take any parameter FILE POSITIONS
  • 37.
    EXAMPLE 1:- Update databinary file containing list of dictionary (d={“Name”:”ana”, “Class”:12}). UPDATE BINARY FILE import pickle f=open("abc.dat",'rb+') x=pickle.load(f) for i in x: if i['Name']=='a yesha': i['Class']=12 print("updated") f.seek(0) pickle.dump(x,f) # pickle is used for binary file # read data # iterate through all data #check condition #modify data # send file pointer to beginning of file # write modified data into file # close file
  • 38.
    • csv moduleprovides classes that assist in the reading and writing of Comma Separated Value (CSV) files • Statement to import csv module:- import csv • To open a csv file, use open() function as used previously in text and binary file. • Syntax:- • • To close a csv file, use close() function as used previously in text and binary file. • Syntax:- file_object.close() file_object=open(‘filename.csv', ‘mode') f=open('data.csv', 'w') CSV MODULE
  • 39.
    • csv.reader :-It is a built-in function in module csv. It take file object as an argument and The returned object is an iterator. Each iteration returns a row of the CSV file • Syntax:- csv_reader = csv.reader( file_object) • csv.writer:-It is a built-in function in module csv. It take file object and returns a writer object responsible for converting the user’s data into delimited strings. Writer object have public methods which are used to write content in csv file like writerow() • Syntax :- • wrt=csv.writer(file_object) wrt.writerow(d1,d2,d3) FUNCTION IN CSV MODULE
  • 40.
    EXAMPLE 1:- Write aprogram to read data from csv file and display it. READ FROM CSV FILE import csv f=open('ar.csv', 'r') f_reader = csv.reader(f) for row in f_reader: print (row) f.close() # to use csv file # open csv file in read mode # read data from csv file in form of rows # iterate through all data # process data #close file
  • 41.
    EXAMPLE 1:- Write aprogram to read data from csv file and display it. WRITE DATA INTO CSV FILE import csv f=open('data1.csv', 'w') wrt=csv.writer(f) d={} while True: name=input("enter your name") age=int(input("enter your age")) class_sec=input("enter your class") wrt.writerow([name, age, class_sec]) if input("Enter E for Exit")=="E": break #open csv file in write mode # create a writer object #input data #Write one row in file
  • 42.