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

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

file handling in python using exception statement
file handling in python using exception statementfile handling in python using exception statement
file handling in python using exception statement
srividhyaarajagopal
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptxFILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 
Data File Handling in Python Programming
Data File Handling in Python ProgrammingData File Handling in Python Programming
Data File Handling in Python Programming
gurjeetjuneja
 
Unit V.pptx
Unit V.pptxUnit V.pptx
Unit V.pptx
ShaswatSurya
 
Binary File.pptx
Binary File.pptxBinary File.pptx
Binary File.pptx
MasterDarsh
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
kendriyavidyalayano24
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
SyedAhmed991492
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
Linga Lgs
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileCBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
ShivaniJayaprakash1
 
Python data file handling
Python data file handlingPython data file handling
Python data file handling
ToniyaP1
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
4HG19EC010HARSHITHAH
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnjlecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
file handling in python using exception statement
file handling in python using exception statementfile handling in python using exception statement
file handling in python using exception statement
srividhyaarajagopal
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptxFILE HANDLING COMPUTER SCIENCE -FILES.pptx
FILE HANDLING COMPUTER SCIENCE -FILES.pptx
anushasabhapathy76
 
Data File Handling in Python Programming
Data File Handling in Python ProgrammingData File Handling in Python Programming
Data File Handling in Python Programming
gurjeetjuneja
 
Binary File.pptx
Binary File.pptxBinary File.pptx
Binary File.pptx
MasterDarsh
 
FILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptxFILE INPUT OUTPUT.pptx
FILE INPUT OUTPUT.pptx
ssuserd0df33
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
SyedAhmed991492
 
Microsoft power point chapter 5 file edited
Microsoft power point   chapter 5 file editedMicrosoft power point   chapter 5 file edited
Microsoft power point chapter 5 file edited
Linga Lgs
 
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is hereCHAPTER 2 - FILE HANDLING-txtfile.pdf is here
CHAPTER 2 - FILE HANDLING-txtfile.pdf is here
sidbhat290907
 
FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.FILE HANDLING in python to understand basic operations.
FILE HANDLING in python to understand basic operations.
ssuser00ad4e
 
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary fileCBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
CBSE - Class 12 - Ch -5 -File Handling , access mode,CSV , Binary file
ShivaniJayaprakash1
 
Python data file handling
Python data file handlingPython data file handling
Python data file handling
ToniyaP1
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
Raja Ram Dutta
 
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnjlecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
lecs102.pdf kjolholhkl';l;llkklkhjhjbhjjmnj
MrProfEsOr1
 

Recently uploaded (20)

How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
How to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 SalesHow to Create Quotation Templates Sequence in Odoo 18 Sales
How to Create Quotation Templates Sequence in Odoo 18 Sales
Celine George
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.Artificial intelligence Presented by JM.
Artificial intelligence Presented by JM.
jmansha170
 
Adam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational PsychologyAdam Grant: Transforming Work Culture Through Organizational Psychology
Adam Grant: Transforming Work Culture Through Organizational Psychology
Prachi Shah
 
IDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptxIDF 30min presentation - December 2, 2024.pptx
IDF 30min presentation - December 2, 2024.pptx
ArneeAgligar
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdfAllomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...
EduSkills OECD
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdfUnit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
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”)