SlideShare a Scribd company logo
Chapter - 5
File Handling in PYTHON
File:
 File is the basic unit of storage which used to store the data permanently.
 A file itself is a bunch of bytes stored on some storage device like hard disk or thumb
drive or any secondary storage device
 A file is a sequence of bytes on the disk/permanent storage where a group of related data
is stored. File is created for permanent storage of data.
 In programming, Sometimes, it is not enough to only display the data on the console.
Those data are to be retrieved later on, then the concept of file handling comes.
It is impossible to recover the programmatically generated data again and again. However,
if we need to do so, we may store it onto the file system which is not volatile and can be
accessed every time. Here, comes the need of file handling in Python.
Data file:
The data files are the files that store data pertaining to a specific application,
for later user. The data file can be stored in two ways:
 TEXT FILE
 BINARY FILE
Text File:
A text file stores information in the form of a stream of ASCII or Unicode
character. In text file, each line of text is terminated, with a special character
known as EOL (End of Line) character. In text files, some internal translation
take place when this EOL character is read or written. In python, by default,
this EOL character is the newline character (‘n’) or carriage-return, new line
character(‘rn’)
Type of text file:
i) Regular Text fie: These are the text files which store the text in the same form as typed. Here the new line character(‘n’)
ends the line and the file extension is .txt.
ii) Delimited text file: In these text files, a specific character is sored to separate the values, i.e., after each value, e.g., a
TAB or a COMMA after every value.
 When a tab is used to separate the values stored, these are called TSV files( Tab Separated Values).These files can
take the extension as .txt or .csv
 When the comma is used to separate the values stored, these are called as CSV files(Comma Separated
Values). These files take extension as .csv
Binary File:
A binary file stores the information in the form of stream of bytes. A binary file contains information in the sam format in
which the information is held in memory, i.e., the file content that is returned a raw format. In binary file, there is no
delimiter character for a line and also no translation occur.
 The CSV format is a popular import and export format for spreadsheet and databases.
 The text files can be opened in any text editor and are in human readable form while binary files are not in
human readable form.
 The .exe files, mp3 file, image files are some of the examples of binary files. we can’t read a binary file using a
text editor.
Text File Binary File
Its Bits represent character. Its Bits represent a custom data.
Less prone to get corrupt as change
reflects as soon as made and can be
undone.
Can easily get corrupted, corrupt on even
single bit change
Store only plain text in a file. Can store different types of data (audio,
text,image) in a single file.
Widely used file format and can be
opened in any text editor.
Developed for an application and can
be opened in that application only.
Mostly .txt and .rtf are used as
extensions to text files.
Can have any application defined
extension.
There is a delimiting character There is no delimiting character
DIFFERENCE BETWEEN TEXT FILE AND BINARY FILE
Opening and Closing Files:
File handling in Python enables us to create, update, read, and delete the
data stored on the file system through our python program. The following
operations can be performed on a file.
In Python, File Handling consists of following three steps:
 Open the file.
 Process file i.e perform read or write operation.
 Close the file.
To perform file operation ,it must be opened first, then after reading,
writing, editing operation can be performed. To create any new file
then too it must be opened. On opening of any file ,a file relevant
structure is created in memory as well as memory space is created to
store contents.
Text file Binary file CSV file
READ()
READLINE()
READLINES()
WRITE()
WRITELINES()
DUMP()
LOAD()
CSV.WRITER()
WRITEROW()
WRITEROWS()
CSV.READER()
COMMON FOR ALL THREE TYPES OF FILES
FILE HANDLING FUNCTIONS:
1.The Open( ) Method:
Before any reading or writing operation of any file, it must be opened first. Python provide built in function
open() for it. On calling of this function ,creates file object for file operations.
Syntax
file object = open( file_name, access_mode )
File object: It is an Identifier which acts as an interface between file and the user. It can be called as file
handle.
file_name = name of the file ,enclosed in double quotes.
access_mode= Determines the what kind of operations can be performed with file,like read,write etc.
For example : file1= open(“sample.txt”)
file1= open(“sample.txt”, ”r”)
file mode is optional, default file mode is read only(“r”)
Text file Binary file Description Explanation
‘r’ ‘rb’ Read only File must exist already, otherwise raises I/O error
‘w’ ‘wb’ Write only  If the file does not exist, file is created
 If the file exists, will truncate existing data and
over-write in the file.
‘a’ ‘ab’ Append  File is in write only mode.
 If the file exists, the data in the file is retained and
new data being appended to the end.
 If the file does not exit, python will create a new
file.
FILE ACCESS MODE / FILE OPENING MODE:
The file access mode describes that how the file will be used in the program i.e to read data
from the file or to write data into the file or add the data into the file.
Text file Binary file Description Explanation
‘r+’ ‘ r+b’ or
‘rb+’
Read and
write
 File must exist otherwise error is raised.
 Both reading and writing operations can take place.
‘w+’ ‘w+b’ or
‘wb+’
Write and read  File is created if does not exist.
 If file exists, file is truncated.
 Both reading and writing operations can take place.
‘a+’ ‘a+b’ or
‘ab+’
Write and read  File is created if does not exist.
 If file exists, file’s existing data is retained, new data
is appended.
 Both reading and writing operations can take place.
2. The close() Method:
close(): Used to close an open file. After using this method, an opened file will be closed.
F1 = open(“sample.txt”, “w”)
-----
-----
F1.close()
3. The write() Method
It writes a string the text file.
Syntax:
File-handle. Write( string variable)
Example: s1=“Venkat International public school n“
s2=“Affiliated to CBSE n ”
F1.write(s1)
F1.write(s2)
4. The writelines( ) Method:
It is used to write all the strings in the list as lines to the text file referenced by the file handle.
Systax:
File-Handle.writelines(list)
Example:
f1= open(“sample.txt”, “w”)
l= [ ]
s1=“Venkat International public school “
s2=“nAffiliated to CBSE”
l.append(s1)
l.append(s2)
f1.writelines(l)
Sample.txt
Venkat International Public School
Affiliated to CBSE
5. The read() Method
It reads the entire file and returns it contents in the form of a string. Reads at most size bytes or less if end of
file occurs. If size not mentioned then read the entire file contents.
Syntax:
File_Handle.read( [ size] )
- size is optional
Example:
f = open(“sample.txt” , ”r”)
1. s= f. read( )
print(s)
o/p: Venkat International Public School
Affiliated to CBSE”
2. s= f.read(6)
print(s)
s=f.read(14)
print(s)
o/p: Venkat
International
6. The readline([size]) method:
It reads a line of input, if n is specified read at most n byte( n characters ) from the text file. It returns the
data in the form string ending with newline (‘n’) character or returns a blank string if no more bytes are left
for reading in the file.
Syntax:
FileHandle.readline( )
Example:
1. f = open(“sample.txt” , ”r”)
s=f.readline()
print(s)
s= f.readline()
print(s)
o/p:
Venkat International Public School
Affiliated to CBSE
2. s=f.readline(20)
print(s)
o/p: Venkat International
7. The readlines( ) method:
It reads all lines from the text file and returns them in a list.
Syntax:
FileHandle.readlines( )
Example:
1. f = open(“sample.txt” , ”r”)
s=f.readlines()
print(s)
o/p:
[“Venkat International Public Schooln”, “Affiliated to CBSEn” ]
2. L =f.readlines()
for i in L:
print(i)
o/p:
Venkat International Public School
Affiliated to CBSE
Operations on Binary file:
Pickle Module:
dump()- It is used to store an object( list or dictionary or tuple…) into a binary
file.
Syntax:
pickle.dump( objectname, file_handle)
Example:
f1=open(“student.dat”, ”wb” )
Rec = [1001,”Raj kumar”, 98.5]
pickle.dump(Rec,f1)
Load( ) - It is used to read an object( list or dictionary or tuple…) from a binary
file.
Syntax:
objectname = pickle.load( file_handle)
Example:
f1=open(“student.dat”, ”rb”)
Rec= pickle.load(f1)
Rec[0]= 1001
Rec[1]=Raj kumar
Rec[2]=98.5
FILE HANDLING IN PYTHON Presentation Computer Science
import pickle
def Create( ):
f1= open("employee.dat","wb")
while True:
empid= int(input("Enter the employee id : "))
ename=input("Enter the employee name ")
salary=int(input("Enter the Salary "))
Rec= [empid, ename, salary ]
pickle.dump(Rec, f1 )
ch=input("Do you want to create another record y/ n ")
if ch=="n" or ch=="N":
break
f1.close()
FILE HANDLING IN PYTHON Presentation Computer Science
def Display():
f1=open("employee.dat","rb")
try:
while True:
Rec=pickle.load( f1 )
print("Employee Id :", Rec[0])
print("Employee Name :", Rec[1])
print("Salary :", Rec[2])
print( )
except EOFError:
f1.close()
CSV FILES
The separator character of CSV files is called a delimiter. Default and most
popular delimiter is comma. Other popular delimiters include the tab (t),
colon(:), pipe(|) and semi-colon(;) characters.
The csv module of python provides functionality to read and write tabular data
in csv format. It provides two specific types of objects- the reader object and
writer objects- to read and write into CSV files. The csv module’s reader and
writer objects read and write delimited sequences as records in a CSV files.
Opening a CSV file:
Syntax:
File-handle = open(“filename.csv”, “mode” [, newline=’n’])
csv.writer( )
csv files are delimited flat files and before writing onto them, the data must be in
csv-writable-delimited form, it is important to convert the received user data into the form
appropriate for the csv files.
This task is performed by the writer object.
Systax:
Writer-object-name= csv.writer(file-handle[, delimiter character] )
example:
wr= csv.writer(f1, delimiter=‘,’)
csv.wrirerow( ): it writes one row of information onto the csv-file.
Syntax:
Writer-object.writerow(sequence )
csv.wrirerows( ): it writes multiple rows of information onto the csv-file.
Syntax:
Writer-object.writerows(sequence )
csv.reader():
The csv reader object loads data from the csv file, parses it, ie removes
the delimiters and returns the data in the form of a python iterable
wherefrom we can fetch one row of data at a time.
Syntax:
List= cse.reader(filehandle [, delimiter=‘ delimiter character])
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
FILE HANDLING IN PYTHON Presentation Computer Science
Random Access on file:
tell( ) - functions returns the current position of file pointer
in the file.
Syntax:
File-object.tell()
Initial position of file pointer is zero.
seek() -function changes the position of file pointer to the
specified place in the file.
Systax:
File-object.seek(offset ,[ mode])
Offset- specify the no. of bytes
Mode – 0 from beginning of the file
1 from the current position
2 from the end of the file.
Sample.txt
The csv module of python provides functionality to read
and write tabular data in csv format. It provides two
specific types of objects- the reader object and writer
objects- to read and write into CSV files. The csv
module’s reader and writer objects read and write
delimited sequences as records in a CSV files.
F1= open(“sample.txt”, “r”)

More Related Content

PPTX
file handling.pptx avlothaan pa thambi popa
PDF
file handling.pdf
PDF
FileHandling2023_Text File.pdf CBSE 2014
PPTX
01 file handling for class use class pptx
PDF
Python file handling
PPTX
5-filehandling-2004054567151830 (1).pptx
PPTX
File Handling in Python -binary files.pptx
PDF
File handling with python class 12th .pdf
file handling.pptx avlothaan pa thambi popa
file handling.pdf
FileHandling2023_Text File.pdf CBSE 2014
01 file handling for class use class pptx
Python file handling
5-filehandling-2004054567151830 (1).pptx
File Handling in Python -binary files.pptx
File handling with python class 12th .pdf

Similar to FILE HANDLING IN PYTHON Presentation Computer Science (20)

PPTX
file handling in python using exception statement
PPTX
DFH PDF-converted.pptx
PPTX
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
PPTX
Chapter 08 data file handling
PPTX
Data File Handling in Python Programming
PPTX
Unit V.pptx
PPTX
Binary File.pptx
PPTX
FILE HANDLING.pptx
PPTX
Chapter - 5.pptx
PPTX
FILE INPUT OUTPUT.pptx
PDF
chapter-4-data-file-handlingeng.pdf
PDF
Microsoft power point chapter 5 file edited
PDF
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
PPTX
FILE HANDLING in python to understand basic operations.
PPTX
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
PPTX
Python data file handling
PPT
File Handling as 08032021 (1).ppt
PDF
Module2-Files.pdf
PDF
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
PDF
File handling3.pdf
file handling in python using exception statement
DFH PDF-converted.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
Chapter 08 data file handling
Data File Handling in Python Programming
Unit V.pptx
Binary File.pptx
FILE HANDLING.pptx
Chapter - 5.pptx
FILE INPUT OUTPUT.pptx
chapter-4-data-file-handlingeng.pdf
Microsoft power point chapter 5 file edited
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
FILE HANDLING in python to understand basic operations.
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
Python data file handling
File Handling as 08032021 (1).ppt
Module2-Files.pdf
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
File handling3.pdf
Ad

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Business Ethics Teaching Materials for college
PDF
Pre independence Education in Inndia.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Cell Types and Its function , kingdom of life
PDF
RMMM.pdf make it easy to upload and study
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Institutional Correction lecture only . . .
Final Presentation General Medicine 03-08-2024.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Business Ethics Teaching Materials for college
Pre independence Education in Inndia.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
01-Introduction-to-Information-Management.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
PPH.pptx obstetrics and gynecology in nursing
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Abdominal Access Techniques with Prof. Dr. R K Mishra
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
FourierSeries-QuestionsWithAnswers(Part-A).pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Supply Chain Operations Speaking Notes -ICLT Program
Cell Types and Its function , kingdom of life
RMMM.pdf make it easy to upload and study
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Institutional Correction lecture only . . .
Ad

FILE HANDLING IN PYTHON Presentation Computer Science

  • 1. Chapter - 5 File Handling in PYTHON File:  File is the basic unit of storage which used to store the data permanently.  A file itself is a bunch of bytes stored on some storage device like hard disk or thumb drive or any secondary storage device  A file is a sequence of bytes on the disk/permanent storage where a group of related data is stored. File is created for permanent storage of data.  In programming, Sometimes, it is not enough to only display the data on the console. Those data are to be retrieved later on, then the concept of file handling comes. It is impossible to recover the programmatically generated data again and again. However, if we need to do so, we may store it onto the file system which is not volatile and can be accessed every time. Here, comes the need of file handling in Python.
  • 2. Data file: The data files are the files that store data pertaining to a specific application, for later user. The data file can be stored in two ways:  TEXT FILE  BINARY FILE Text File: A text file stores information in the form of a stream of ASCII or Unicode character. In text file, each line of text is terminated, with a special character known as EOL (End of Line) character. In text files, some internal translation take place when this EOL character is read or written. In python, by default, this EOL character is the newline character (‘n’) or carriage-return, new line character(‘rn’)
  • 3. Type of text file: i) Regular Text fie: These are the text files which store the text in the same form as typed. Here the new line character(‘n’) ends the line and the file extension is .txt. ii) Delimited text file: In these text files, a specific character is sored to separate the values, i.e., after each value, e.g., a TAB or a COMMA after every value.  When a tab is used to separate the values stored, these are called TSV files( Tab Separated Values).These files can take the extension as .txt or .csv  When the comma is used to separate the values stored, these are called as CSV files(Comma Separated Values). These files take extension as .csv Binary File: A binary file stores the information in the form of stream of bytes. A binary file contains information in the sam format in which the information is held in memory, i.e., the file content that is returned a raw format. In binary file, there is no delimiter character for a line and also no translation occur.  The CSV format is a popular import and export format for spreadsheet and databases.  The text files can be opened in any text editor and are in human readable form while binary files are not in human readable form.  The .exe files, mp3 file, image files are some of the examples of binary files. we can’t read a binary file using a text editor.
  • 4. Text File Binary File Its Bits represent character. Its Bits represent a custom data. Less prone to get corrupt as change reflects as soon as made and can be undone. Can easily get corrupted, corrupt on even single bit change Store only plain text in a file. Can store different types of data (audio, text,image) in a single file. Widely used file format and can be opened in any text editor. Developed for an application and can be opened in that application only. Mostly .txt and .rtf are used as extensions to text files. Can have any application defined extension. There is a delimiting character There is no delimiting character DIFFERENCE BETWEEN TEXT FILE AND BINARY FILE
  • 5. Opening and Closing Files: File handling in Python enables us to create, update, read, and delete the data stored on the file system through our python program. The following operations can be performed on a file. In Python, File Handling consists of following three steps:  Open the file.  Process file i.e perform read or write operation.  Close the file. To perform file operation ,it must be opened first, then after reading, writing, editing operation can be performed. To create any new file then too it must be opened. On opening of any file ,a file relevant structure is created in memory as well as memory space is created to store contents.
  • 6. Text file Binary file CSV file READ() READLINE() READLINES() WRITE() WRITELINES() DUMP() LOAD() CSV.WRITER() WRITEROW() WRITEROWS() CSV.READER() COMMON FOR ALL THREE TYPES OF FILES FILE HANDLING FUNCTIONS:
  • 7. 1.The Open( ) Method: Before any reading or writing operation of any file, it must be opened first. Python provide built in function open() for it. On calling of this function ,creates file object for file operations. Syntax file object = open( file_name, access_mode ) File object: It is an Identifier which acts as an interface between file and the user. It can be called as file handle. file_name = name of the file ,enclosed in double quotes. access_mode= Determines the what kind of operations can be performed with file,like read,write etc. For example : file1= open(“sample.txt”) file1= open(“sample.txt”, ”r”) file mode is optional, default file mode is read only(“r”)
  • 8. Text file Binary file Description Explanation ‘r’ ‘rb’ Read only File must exist already, otherwise raises I/O error ‘w’ ‘wb’ Write only  If the file does not exist, file is created  If the file exists, will truncate existing data and over-write in the file. ‘a’ ‘ab’ Append  File is in write only mode.  If the file exists, the data in the file is retained and new data being appended to the end.  If the file does not exit, python will create a new file. FILE ACCESS MODE / FILE OPENING MODE: The file access mode describes that how the file will be used in the program i.e to read data from the file or to write data into the file or add the data into the file.
  • 9. Text file Binary file Description Explanation ‘r+’ ‘ r+b’ or ‘rb+’ Read and write  File must exist otherwise error is raised.  Both reading and writing operations can take place. ‘w+’ ‘w+b’ or ‘wb+’ Write and read  File is created if does not exist.  If file exists, file is truncated.  Both reading and writing operations can take place. ‘a+’ ‘a+b’ or ‘ab+’ Write and read  File is created if does not exist.  If file exists, file’s existing data is retained, new data is appended.  Both reading and writing operations can take place.
  • 10. 2. The close() Method: close(): Used to close an open file. After using this method, an opened file will be closed. F1 = open(“sample.txt”, “w”) ----- ----- F1.close() 3. The write() Method It writes a string the text file. Syntax: File-handle. Write( string variable) Example: s1=“Venkat International public school n“ s2=“Affiliated to CBSE n ” F1.write(s1) F1.write(s2)
  • 11. 4. The writelines( ) Method: It is used to write all the strings in the list as lines to the text file referenced by the file handle. Systax: File-Handle.writelines(list) Example: f1= open(“sample.txt”, “w”) l= [ ] s1=“Venkat International public school “ s2=“nAffiliated to CBSE” l.append(s1) l.append(s2) f1.writelines(l) Sample.txt Venkat International Public School Affiliated to CBSE
  • 12. 5. The read() Method It reads the entire file and returns it contents in the form of a string. Reads at most size bytes or less if end of file occurs. If size not mentioned then read the entire file contents. Syntax: File_Handle.read( [ size] ) - size is optional Example: f = open(“sample.txt” , ”r”) 1. s= f. read( ) print(s) o/p: Venkat International Public School Affiliated to CBSE” 2. s= f.read(6) print(s) s=f.read(14) print(s) o/p: Venkat International
  • 13. 6. The readline([size]) method: It reads a line of input, if n is specified read at most n byte( n characters ) from the text file. It returns the data in the form string ending with newline (‘n’) character or returns a blank string if no more bytes are left for reading in the file. Syntax: FileHandle.readline( ) Example: 1. f = open(“sample.txt” , ”r”) s=f.readline() print(s) s= f.readline() print(s) o/p: Venkat International Public School Affiliated to CBSE 2. s=f.readline(20) print(s) o/p: Venkat International
  • 14. 7. The readlines( ) method: It reads all lines from the text file and returns them in a list. Syntax: FileHandle.readlines( ) Example: 1. f = open(“sample.txt” , ”r”) s=f.readlines() print(s) o/p: [“Venkat International Public Schooln”, “Affiliated to CBSEn” ] 2. L =f.readlines() for i in L: print(i) o/p: Venkat International Public School Affiliated to CBSE
  • 15. Operations on Binary file: Pickle Module: dump()- It is used to store an object( list or dictionary or tuple…) into a binary file. Syntax: pickle.dump( objectname, file_handle) Example: f1=open(“student.dat”, ”wb” ) Rec = [1001,”Raj kumar”, 98.5] pickle.dump(Rec,f1)
  • 16. Load( ) - It is used to read an object( list or dictionary or tuple…) from a binary file. Syntax: objectname = pickle.load( file_handle) Example: f1=open(“student.dat”, ”rb”) Rec= pickle.load(f1) Rec[0]= 1001 Rec[1]=Raj kumar Rec[2]=98.5
  • 18. import pickle def Create( ): f1= open("employee.dat","wb") while True: empid= int(input("Enter the employee id : ")) ename=input("Enter the employee name ") salary=int(input("Enter the Salary ")) Rec= [empid, ename, salary ] pickle.dump(Rec, f1 ) ch=input("Do you want to create another record y/ n ") if ch=="n" or ch=="N": break f1.close()
  • 20. def Display(): f1=open("employee.dat","rb") try: while True: Rec=pickle.load( f1 ) print("Employee Id :", Rec[0]) print("Employee Name :", Rec[1]) print("Salary :", Rec[2]) print( ) except EOFError: f1.close()
  • 21. CSV FILES The separator character of CSV files is called a delimiter. Default and most popular delimiter is comma. Other popular delimiters include the tab (t), colon(:), pipe(|) and semi-colon(;) characters. The csv module of python provides functionality to read and write tabular data in csv format. It provides two specific types of objects- the reader object and writer objects- to read and write into CSV files. The csv module’s reader and writer objects read and write delimited sequences as records in a CSV files. Opening a CSV file: Syntax: File-handle = open(“filename.csv”, “mode” [, newline=’n’])
  • 22. csv.writer( ) csv files are delimited flat files and before writing onto them, the data must be in csv-writable-delimited form, it is important to convert the received user data into the form appropriate for the csv files. This task is performed by the writer object. Systax: Writer-object-name= csv.writer(file-handle[, delimiter character] ) example: wr= csv.writer(f1, delimiter=‘,’)
  • 23. csv.wrirerow( ): it writes one row of information onto the csv-file. Syntax: Writer-object.writerow(sequence ) csv.wrirerows( ): it writes multiple rows of information onto the csv-file. Syntax: Writer-object.writerows(sequence )
  • 24. csv.reader(): The csv reader object loads data from the csv file, parses it, ie removes the delimiters and returns the data in the form of a python iterable wherefrom we can fetch one row of data at a time. Syntax: List= cse.reader(filehandle [, delimiter=‘ delimiter character])
  • 29. Random Access on file: tell( ) - functions returns the current position of file pointer in the file. Syntax: File-object.tell() Initial position of file pointer is zero.
  • 30. seek() -function changes the position of file pointer to the specified place in the file. Systax: File-object.seek(offset ,[ mode]) Offset- specify the no. of bytes Mode – 0 from beginning of the file 1 from the current position 2 from the end of the file.
  • 31. Sample.txt The csv module of python provides functionality to read and write tabular data in csv format. It provides two specific types of objects- the reader object and writer objects- to read and write into CSV files. The csv module’s reader and writer objects read and write delimited sequences as records in a CSV files. F1= open(“sample.txt”, “r”)