SlideShare a Scribd company logo
1 of 50
UNIT 5
Files and Exception
Handling
Introduction – Text Input and Output – File
Dialogs – Retrieving Data from the Web –
Exception Handling - Raising Exceptions –
Processing Exception using Exception Objects
– Defining Custom Exception Classes.
Files – Definition
• A collection of data or information write into
notepad and save those information called file.
• All the information stored in a computer must be
in a file.
• File is a named location on disk to store related
information.
• It is used to permanently store data in non-
volatile memory (e.g. hard disk), Since, random
access memory (RAM) is volatile which loses its
data when computer is turned off,
• we use files for future use of the data.
ANGURAJU AP/CSE
There are different types of files, they
are listed below:
I. Data files
II. Text files
III. Program files
IV. Directory files, and so on.
Different types of files store different types
of information.
ANGURAJU AP/CSE
1. Sequential access
This type of file is to be accessed sequentially ,
Here we want to access the last record in a file you
must read all the records sequentially . It takes more
time for accessing the record.
2. Random access
This type of file allows access to the specific
data directly with out accessing its preceding data
items.
Here the data can be accessed and modified
randomly.
Types of file accessing
File Operations /Text input and
output
Whenever the user wants to read or write
into a file we need to open it first, after read
write process, then it needs to be closed,
then only you avoid data losses.
1. Open the file
2. Read or write
3. Close the file
ANGURAJU AP/CSE
File open function
Python has a built-in function open() to open a file.
This function returns a file object, so it is most commonly
used with two arguments.
Syntax:
file_object = open(“filename”, [“access
mode”],[“buffering”])
Access mode – it determine the mode in which the file has to
be opened
Buffering – 0 , 1
if 0 no buffering
if 1 line buffering is performed while accessing a file
file_object - Once a file is opened and you have one file object
ANGURAJU AP/CSE
Example
file object name = open(“file name.txt”,
“accessing Mode”)
Example:
f= open(“student.txt”, “w”)
With /as Statement
The user can also work with file objects using the with
statement. It is designed to provide much cleaner syntax
and exceptions handling when you are working with code.
Advantages :
• If any files opened will be closed automatically after you
are done.
To use the with statement to open a file:
Syntax:
with open(“filename” , “access mode”) as file:
Ex :
with open(“sam.txt” , “w”) as file:
file.write(“hai”)
ANGURAJU AP/CSE
File Opening Methods
MODES DESCRIPTION
r Open the file for reading . The file pointer is
placed at beginning of the file .
w Open a file for writing only , overwrites the file
if the file already exist, If the file does not exist ,
create a new file for writing
rb Open the file for reading only in binary format .
The file pointer is placed at the beginning of the
file .
wb Open a file for writing only binary files ,
overwrites the file if the file already exist, If the
file does not exist , create a new file for writing
ANGURAJU AP/CSE
r+ Open the file for reading and writing . The file
pointer is placed at beginning of the file .
w+ Open a file for writing and reading ,
overwrites the file if the file already exist, If
the file does not exist , create a new file for
writing and reading
a Opens the file for appending, The file pointer is
placed at the end of the line .
ab Opens the file for appending in binary format ,
The file pointer is placed at the end of the line .
ANGURAJU AP/CSE
Reading and Writing Files
The file object is used to access a file for
reading and writing. There are two functions
to do this operation
read()
write()
ANGURAJU AP/CSE
Write a text file
Write() method
• This method writes any string to an opened
text file .
• The write() method does not add a newline to
the character(‘n’) to the end of the string
Syntax:
File _object . write(“string”)
ANGURAJU AP/CSE
Example
>>>f = open(“sample.txt”, “w+”) #open a file
>>>f . write(“Problem solving python
programming”) #write a file
>>>print(f.read()) # read a file
>>>f.close() #close a file
OUTPUT:
Problem solving python programming
ANGURAJU AP/CSE
Read the text file
Read() method
• This method reads a string from the opened
text file.
• The read method starts reading from the
beginning of the file .
• The parameter is the number of bytes to be
read from the opened file.
• Syntax:
• fileobject.read(count)
ANGURAJU AP/CSE
readline() function
whenever the user run the method, it will
return a string of characters that contains a
single line of information from the file
file = open(“kk.txt”, “r”)
print file.readline():
Output
Hello World
ANGURAJU AP/CSE
Example
>>> f = open(“sample.txt”,”r+”)
>>> Str=f.read(10)
>>> Print(“the value is “, str)
>>> f.close()
OUTPUT:
Problem py
ANGURAJU AP/CSE
CLOSE THE TEXT FILE
The close() method
The close method closes the file object ,
after the completion of read write process.
Python automatically closes a file when
the reference object of a file reassigned to
another file.
It is good practice to use the close()
method to close a file.
Syntax:
file _ object . close()
ANGURAJU AP/CSE
Random access file /File
Manipulation
There are two major methods,
• Tell()
• Seek()
Tell():
Tells you the current position within the file.
file_object.tell()
ANGURAJU AP/CSE
Seek() -this function read the string based on the offset and
from where into a text file
file_object.seek(offset , from where)
offset – how many bytes to move (eliminate)
from where – which position to move( 0 represent
beginning of the file)
Ex:
file.seek(10,0)
10- move first 10 character
0 – from beginning of file
file.seek(0,0)
0 – move 0 charater
0- read data from the beginning of file
ANGURAJU AP/CSE
Example:
>>> f1=open("w.txt", "w")
>>> f1.write(“ragulraj")
>>> f1.write("ramkumar")
>>> f1.close()
>>> f1=open("w.txt", "r")
>>> f1.read()
‘ragulrajramkumar'
>>> f1.seek(7,0)
>>> f1.read()
'ramkumar‘
>>> f1.seek(0,0)
>>> f1.read()
‘ragulrajramkumar' ANGURAJU AP/CSE
File Dialog
Python Tkinter offer a set of dialogs that
you can use when working with files.
By using these you don’t have to design
standard dialogs your self.
Example dialogs include an open file
dialog, a save file dialog and many others.
Besides file dialogs there are other
standard dialogs,
File dialogs help you open, save files or
directories.
This is the type of dialog you get when you
click file,open.
This dialog comes out of the module,
there’s no need to write all the code manually.
Example:
import tkinter.filedialog
tkinter.filedialog.asksaveasfilename()
tkinter.filedialog.asksaveasfile()
tkinter.filedialog.askopenfilename()
tkinter.filedialog.askopenfile()
tkinter.filedialog.askdirectory()
tkinter.filedialog.askopenfilenames()
tkinter.filedialog.askopenfiles()
Retrieving Data from the web:
You can use the urlopen function to open a
Uniform Resource Locator (URL) and read data
from the Web.
Using Python, you can write simple code to
read data from a Web site.
All you need to do is to open a URL by using
the urlopen function, as follows:
infile =
urllib.request.urlopen("http://www.yahoo.com")
The urlopen function (defined in the
urllib.request module) opens a URL resource like
a file.
Example:
import urllib.request
infile =
urllib.request.urlopen("http://www.yahoo.com
/index.html")
print(infile.read().decode())
The data read from the URL using
infile.read() is raw data in bytes. Invoking the
decode() method converts the raw data to a
string
Errors and Exceptions
Errors:
Errors or mistakes in a program are often
referred to as bugs.
This is made by the programmer.
The process of finding and eliminating
errors is called debugging.
Errors can be classified into three major
groups:
a) Syntax errors
b) Runtime errors
c) Logical errors
ANGURAJU AP/CSE
Syntax error:
Python will find these kinds of errors when
it tries to parse your program,
Syntax errors are mistakes in the use of
the Python language, and spelling or
grammar mistakes in a keyword .
Example:
• leaving out a symbol, such as a colon, comma
or brackets
• misspelling a keyword
• incorrect indentation ….. etc
ANGURAJU AP/CSE
Runtime errors
If a program is syntactically correct that is,
free of syntax errors it will be run by the Python
interpreter.
However, the program may exit unexpectedly
during execution if it encounters a runtime error
which was not detected when the program
was parsed, but is only stop working when a
particular line is executed.
When a program comes to a halt because of a
runtime error, problem
Example:
• division by zero
• performing an operation on incompatible types
ANGURAJU AP/CSE
Logical errors
Logical errors are the most difficult to fix.
They occur when the program runs without
crashing, but produces an incorrect result.
The error is caused by a mistake in the
program’s logic.
Example:
 using the wrong variable name
 indenting a block to the wrong level
 getting operator precedence wrong
ANGURAJU AP/CSE
Handling Exception
An exception is an event, which occurs
during the execution of a program , that
disrupts the normal flow of the program’s
instructions
An exception is a Python object that
represents an error.
When a Python script raises an exception,
it must be handle immediately otherwise it
terminates and quits.
ANGURAJU AP/CSE
Python provides two important features to
handle any unexpected error in the Python
programs.
There are two kinds of exception :
Predefined exception
predefined exception are build in
exception ,it is also called as python object
that handle the errors in the program.
User defined exception :
Assertions
Try .. . Except
ANGURAJU AP/CSE
ANGURAJU AP/CSE
ANGURAJU AP/CSE
Example:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
10 * (1/0)
ZeroDivisionError: division by zero
>>> 4 * a+3
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
4 * a+3
NameError: name 'a' is not defined
ANGURAJU AP/CSE
User defined exception
Assertions
Assertions are carried out by the assert
statement ,
An assertion is a sanity-check that you can
turn on or turn off when you are done with
your testing of the program.
Syntax
assert Expression , [ Arguments]
Example:
assert (no>=0) , [ “ negative number”]
ANGURAJU AP/CSE
Example:
def celtofar(temp):
assert(temp>=0), "Celsius is negative"
return(((temp*1.8)+32))
print(celtofar(36))
print(int(celtofar(37.6)))
print(celtofar(-5))
ANGURAJU AP/CSE
Handling Exception( By using try
except block)
Here using Try Except block to write programs
that handle selected exception.
The try except statement:
First the try execute the statement between
the try
and except keywords is executed.
If no exception accurse, the except portion is
skipped and exeution of the try statement is
finished.
If an exception accurse during execution of
the try portion, the entire statement in try block
are skipped.
EXAMPLE:
try:
x=int(input(“Enter the number”))
except ValueError:
print("That is not a valid number try
again")
Output:
Enter the number “ram”
That is not a valid number try again
Raising an Exception
An exception is thrown by executing the
raise statement.
This will designates the problem.
It can raise a exception using raise
command:
Sysntax:
raise ValueError(“x cannot be negative”)
This syntax raises a newly created instance
of the ValueError class
ANGURAJU AP/CSE
>>> raise KeyboardInterrupt
Traceback (most recent call last):
KeyboardInterrupt
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
MemoryError: This is an argument
try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive
number!")
except ValueError as ex:
print(ex)
Output:
Enter a positive integer: -2
That is not a positive number!
Processing Exceptions Using Exception
Object
In Python possible to access the exception
object in the except clause.
Here we assign the exception object
assigned to variable then it will be handled.
we can use the following syntax to assign the
exception object to a variable.
When the except clause catches the exception,
the exception object is assigned to a new variable
named as ex
Now you can use the object in the exception
handler.
Syntax:
try:
<body of try block>
except Exception Type as ex:
< Handling exception statement>
Example:
try:
n=eval(input("Enter the number"))
print("Entered number is",n)
except NameError as ex:
print("Exception:", ex)
Output:
Enter the number one
Exception: name 'one' is not defined
Defining Custom Exception
Creating Custom Exceptions
In Python, users can define custom
exceptions by creating a new class.
This exception class has to be derived,
either directly or indirectly, from the built-in
Exception class.
Most of the built-in exceptions are also
derived from this class.
Example:
>>> class CustomError(Exception):
pass
>>> raise CustomError
Traceback (most recent call last):
...
__main__.CustomError
>>> raise CustomError("An error occurred")
Traceback (most recent call last):
...
__main__.CustomError: An error occurred
In this to create a class named as
CustomError is derived from the base class
Exception
By using the new class, now raise the
exception using raise keyword.
Example:
class LogError(Exception):
pass
c=int(input("Enter the number"))
if(c>=0):
print("the number is", c)
else:
raise LogError("Enter only passitive number",)

More Related Content

Similar to UNIT 5.pptx

Similar to UNIT 5.pptx (20)

File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
Module2-Files.pdf
Module2-Files.pdfModule2-Files.pdf
Module2-Files.pdf
 
File Handling in C Part I
File Handling in C Part IFile Handling in C Part I
File Handling in C Part I
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
File handling
File handlingFile handling
File handling
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
File management
File managementFile management
File management
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
Python file handling
Python file handlingPython file handling
Python file handling
 
File handling C program
File handling C programFile handling C program
File handling C program
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
03-01-File Handling.pdf
03-01-File Handling.pdf03-01-File Handling.pdf
03-01-File Handling.pdf
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
 

More from Kongunadu College of Engineering and Technology (19)

Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptx
 
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
Unit - 1.ppt
 
Unit - 2.ppt
Unit - 2.pptUnit - 2.ppt
Unit - 2.ppt
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
U1.ppt
U1.pptU1.ppt
U1.ppt
 
U2.ppt
U2.pptU2.ppt
U2.ppt
 
U4.ppt
U4.pptU4.ppt
U4.ppt
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U3.pptx
U3.pptxU3.pptx
U3.pptx
 

Recently uploaded

Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 

Recently uploaded (20)

Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
VICTOR MAESTRE RAMIREZ - Planetary Defender on NASA's Double Asteroid Redirec...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 

UNIT 5.pptx

  • 1. UNIT 5 Files and Exception Handling
  • 2. Introduction – Text Input and Output – File Dialogs – Retrieving Data from the Web – Exception Handling - Raising Exceptions – Processing Exception using Exception Objects – Defining Custom Exception Classes.
  • 3. Files – Definition • A collection of data or information write into notepad and save those information called file. • All the information stored in a computer must be in a file. • File is a named location on disk to store related information. • It is used to permanently store data in non- volatile memory (e.g. hard disk), Since, random access memory (RAM) is volatile which loses its data when computer is turned off, • we use files for future use of the data. ANGURAJU AP/CSE
  • 4. There are different types of files, they are listed below: I. Data files II. Text files III. Program files IV. Directory files, and so on. Different types of files store different types of information. ANGURAJU AP/CSE
  • 5. 1. Sequential access This type of file is to be accessed sequentially , Here we want to access the last record in a file you must read all the records sequentially . It takes more time for accessing the record. 2. Random access This type of file allows access to the specific data directly with out accessing its preceding data items. Here the data can be accessed and modified randomly. Types of file accessing
  • 6. File Operations /Text input and output Whenever the user wants to read or write into a file we need to open it first, after read write process, then it needs to be closed, then only you avoid data losses. 1. Open the file 2. Read or write 3. Close the file ANGURAJU AP/CSE
  • 7. File open function Python has a built-in function open() to open a file. This function returns a file object, so it is most commonly used with two arguments. Syntax: file_object = open(“filename”, [“access mode”],[“buffering”]) Access mode – it determine the mode in which the file has to be opened Buffering – 0 , 1 if 0 no buffering if 1 line buffering is performed while accessing a file file_object - Once a file is opened and you have one file object ANGURAJU AP/CSE
  • 8. Example file object name = open(“file name.txt”, “accessing Mode”) Example: f= open(“student.txt”, “w”)
  • 9. With /as Statement The user can also work with file objects using the with statement. It is designed to provide much cleaner syntax and exceptions handling when you are working with code. Advantages : • If any files opened will be closed automatically after you are done. To use the with statement to open a file: Syntax: with open(“filename” , “access mode”) as file: Ex : with open(“sam.txt” , “w”) as file: file.write(“hai”) ANGURAJU AP/CSE
  • 10. File Opening Methods MODES DESCRIPTION r Open the file for reading . The file pointer is placed at beginning of the file . w Open a file for writing only , overwrites the file if the file already exist, If the file does not exist , create a new file for writing rb Open the file for reading only in binary format . The file pointer is placed at the beginning of the file . wb Open a file for writing only binary files , overwrites the file if the file already exist, If the file does not exist , create a new file for writing ANGURAJU AP/CSE
  • 11. r+ Open the file for reading and writing . The file pointer is placed at beginning of the file . w+ Open a file for writing and reading , overwrites the file if the file already exist, If the file does not exist , create a new file for writing and reading a Opens the file for appending, The file pointer is placed at the end of the line . ab Opens the file for appending in binary format , The file pointer is placed at the end of the line . ANGURAJU AP/CSE
  • 12. Reading and Writing Files The file object is used to access a file for reading and writing. There are two functions to do this operation read() write() ANGURAJU AP/CSE
  • 13. Write a text file Write() method • This method writes any string to an opened text file . • The write() method does not add a newline to the character(‘n’) to the end of the string Syntax: File _object . write(“string”) ANGURAJU AP/CSE
  • 14. Example >>>f = open(“sample.txt”, “w+”) #open a file >>>f . write(“Problem solving python programming”) #write a file >>>print(f.read()) # read a file >>>f.close() #close a file OUTPUT: Problem solving python programming ANGURAJU AP/CSE
  • 15. Read the text file Read() method • This method reads a string from the opened text file. • The read method starts reading from the beginning of the file . • The parameter is the number of bytes to be read from the opened file. • Syntax: • fileobject.read(count) ANGURAJU AP/CSE
  • 16. readline() function whenever the user run the method, it will return a string of characters that contains a single line of information from the file file = open(“kk.txt”, “r”) print file.readline(): Output Hello World ANGURAJU AP/CSE
  • 17. Example >>> f = open(“sample.txt”,”r+”) >>> Str=f.read(10) >>> Print(“the value is “, str) >>> f.close() OUTPUT: Problem py ANGURAJU AP/CSE
  • 18. CLOSE THE TEXT FILE The close() method The close method closes the file object , after the completion of read write process. Python automatically closes a file when the reference object of a file reassigned to another file. It is good practice to use the close() method to close a file. Syntax: file _ object . close() ANGURAJU AP/CSE
  • 19. Random access file /File Manipulation There are two major methods, • Tell() • Seek() Tell(): Tells you the current position within the file. file_object.tell() ANGURAJU AP/CSE
  • 20. Seek() -this function read the string based on the offset and from where into a text file file_object.seek(offset , from where) offset – how many bytes to move (eliminate) from where – which position to move( 0 represent beginning of the file) Ex: file.seek(10,0) 10- move first 10 character 0 – from beginning of file file.seek(0,0) 0 – move 0 charater 0- read data from the beginning of file ANGURAJU AP/CSE
  • 21. Example: >>> f1=open("w.txt", "w") >>> f1.write(“ragulraj") >>> f1.write("ramkumar") >>> f1.close() >>> f1=open("w.txt", "r") >>> f1.read() ‘ragulrajramkumar' >>> f1.seek(7,0) >>> f1.read() 'ramkumar‘ >>> f1.seek(0,0) >>> f1.read() ‘ragulrajramkumar' ANGURAJU AP/CSE
  • 22. File Dialog Python Tkinter offer a set of dialogs that you can use when working with files. By using these you don’t have to design standard dialogs your self. Example dialogs include an open file dialog, a save file dialog and many others. Besides file dialogs there are other standard dialogs,
  • 23. File dialogs help you open, save files or directories. This is the type of dialog you get when you click file,open. This dialog comes out of the module, there’s no need to write all the code manually.
  • 25. Retrieving Data from the web: You can use the urlopen function to open a Uniform Resource Locator (URL) and read data from the Web. Using Python, you can write simple code to read data from a Web site. All you need to do is to open a URL by using the urlopen function, as follows: infile = urllib.request.urlopen("http://www.yahoo.com") The urlopen function (defined in the urllib.request module) opens a URL resource like a file.
  • 26. Example: import urllib.request infile = urllib.request.urlopen("http://www.yahoo.com /index.html") print(infile.read().decode()) The data read from the URL using infile.read() is raw data in bytes. Invoking the decode() method converts the raw data to a string
  • 27. Errors and Exceptions Errors: Errors or mistakes in a program are often referred to as bugs. This is made by the programmer. The process of finding and eliminating errors is called debugging. Errors can be classified into three major groups: a) Syntax errors b) Runtime errors c) Logical errors ANGURAJU AP/CSE
  • 28. Syntax error: Python will find these kinds of errors when it tries to parse your program, Syntax errors are mistakes in the use of the Python language, and spelling or grammar mistakes in a keyword . Example: • leaving out a symbol, such as a colon, comma or brackets • misspelling a keyword • incorrect indentation ….. etc ANGURAJU AP/CSE
  • 29. Runtime errors If a program is syntactically correct that is, free of syntax errors it will be run by the Python interpreter. However, the program may exit unexpectedly during execution if it encounters a runtime error which was not detected when the program was parsed, but is only stop working when a particular line is executed. When a program comes to a halt because of a runtime error, problem Example: • division by zero • performing an operation on incompatible types ANGURAJU AP/CSE
  • 30. Logical errors Logical errors are the most difficult to fix. They occur when the program runs without crashing, but produces an incorrect result. The error is caused by a mistake in the program’s logic. Example:  using the wrong variable name  indenting a block to the wrong level  getting operator precedence wrong ANGURAJU AP/CSE
  • 31. Handling Exception An exception is an event, which occurs during the execution of a program , that disrupts the normal flow of the program’s instructions An exception is a Python object that represents an error. When a Python script raises an exception, it must be handle immediately otherwise it terminates and quits. ANGURAJU AP/CSE
  • 32. Python provides two important features to handle any unexpected error in the Python programs. There are two kinds of exception : Predefined exception predefined exception are build in exception ,it is also called as python object that handle the errors in the program. User defined exception : Assertions Try .. . Except ANGURAJU AP/CSE
  • 35. Example: >>> 10 * (1/0) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> 10 * (1/0) ZeroDivisionError: division by zero >>> 4 * a+3 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> 4 * a+3 NameError: name 'a' is not defined ANGURAJU AP/CSE
  • 36. User defined exception Assertions Assertions are carried out by the assert statement , An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program. Syntax assert Expression , [ Arguments] Example: assert (no>=0) , [ “ negative number”] ANGURAJU AP/CSE
  • 37. Example: def celtofar(temp): assert(temp>=0), "Celsius is negative" return(((temp*1.8)+32)) print(celtofar(36)) print(int(celtofar(37.6))) print(celtofar(-5)) ANGURAJU AP/CSE
  • 38. Handling Exception( By using try except block) Here using Try Except block to write programs that handle selected exception. The try except statement: First the try execute the statement between the try and except keywords is executed. If no exception accurse, the except portion is skipped and exeution of the try statement is finished. If an exception accurse during execution of the try portion, the entire statement in try block are skipped.
  • 39. EXAMPLE: try: x=int(input(“Enter the number”)) except ValueError: print("That is not a valid number try again") Output: Enter the number “ram” That is not a valid number try again
  • 40. Raising an Exception An exception is thrown by executing the raise statement. This will designates the problem. It can raise a exception using raise command: Sysntax: raise ValueError(“x cannot be negative”) This syntax raises a newly created instance of the ValueError class ANGURAJU AP/CSE
  • 41. >>> raise KeyboardInterrupt Traceback (most recent call last): KeyboardInterrupt >>> raise MemoryError("This is an argument") Traceback (most recent call last): MemoryError: This is an argument
  • 42. try: a = int(input("Enter a positive integer: ")) if a <= 0: raise ValueError("That is not a positive number!") except ValueError as ex: print(ex) Output: Enter a positive integer: -2 That is not a positive number!
  • 43. Processing Exceptions Using Exception Object In Python possible to access the exception object in the except clause. Here we assign the exception object assigned to variable then it will be handled.
  • 44. we can use the following syntax to assign the exception object to a variable. When the except clause catches the exception, the exception object is assigned to a new variable named as ex Now you can use the object in the exception handler. Syntax: try: <body of try block> except Exception Type as ex: < Handling exception statement>
  • 45. Example: try: n=eval(input("Enter the number")) print("Entered number is",n) except NameError as ex: print("Exception:", ex) Output: Enter the number one Exception: name 'one' is not defined
  • 46. Defining Custom Exception Creating Custom Exceptions In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class.
  • 47.
  • 48. Example: >>> class CustomError(Exception): pass >>> raise CustomError Traceback (most recent call last): ... __main__.CustomError >>> raise CustomError("An error occurred") Traceback (most recent call last): ... __main__.CustomError: An error occurred
  • 49. In this to create a class named as CustomError is derived from the base class Exception By using the new class, now raise the exception using raise keyword.
  • 50. Example: class LogError(Exception): pass c=int(input("Enter the number")) if(c>=0): print("the number is", c) else: raise LogError("Enter only passitive number",)