0% found this document useful (0 votes)
56 views

Files and Exceptions

The document discusses file handling and exception handling in Python. It describes opening, reading, writing, and closing files. It also discusses different types of exceptions like syntax errors, ZeroDivisionError, IndexError, and how to handle exceptions using try, except, else and finally blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Files and Exceptions

The document discusses file handling and exception handling in Python. It describes opening, reading, writing, and closing files. It also discusses different types of exceptions like syntax errors, ZeroDivisionError, IndexError, and how to handle exceptions using try, except, else and finally blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Files Handling and

Exceptions Handling
File handling:
• File handling in Python is a powerful and versatile tool that can be
used to perform a wide range of operations.
• Python too supports file handling and allows users to handle files i.e.,
to read and write files, along with many other file handling options, to
operate on files.
• In Python, file handling is a critical aspect that allows you to work with files on
your computer. The built-in open() function is commonly used for file handling.
Here's a basic overview:

• Opening a File:
• To open a file, you use the open() function. It takes two arguments: the name of
the file and the mode in which you want to open the file. Modes include:

• 'r': Read (default mode). Opens the file for reading.


• 'w': Write. Opens the file for writing. Creates a new file if it doesn't exist or
truncates the file if it exists.
• 'a': Append. Opens the file for writing. Creates a new file if it doesn't exist. If the
file exists, it appends the content to the end.
• 'b': Binary mode. Used in combination with other modes, e.g., 'rb' or 'wb'.
#Example: Opening a file for reading
• file = open('example.txt', 'r')
• Reading from a File:
• You can read the contents of a file using methods like read(),
readline(), or readlines().
# Reading the entire content
• content = file.read()
• print(content)

# Reading a single line


• line = file.readline()
• print(line)

# Reading all lines into a list


• lines = file.readlines()
• print(lines)
Writing to a File:
• You can write to a file using the write() method.
• # Writing to a file
• file = open('example.txt', 'w')
• file.write('This is a new line.')
• Closing a File:
• It's important to close the file using the close() method when you're
done with it.
• # Closing the file
• file.close()
Using with Statement:
• To ensure that a file is properly closed after usage, you can use the
with statement. It automatically takes care of closing the file, even if
an exception occurs.

# Using with statement


• with open('example.txt', 'r') as file:
• content = file.read()
# Do something with the content
# File is automatically closed after exiting the 'with' block
Appending to a File:
• To append content to an existing file, use the 'a' mode.
# Appending to a file
• with open('example.txt', 'a') as file:
• file.write('\nThis line is appended.')
Python Exceptions

• An exception is an unexpected event that occurs during program


execution. For example,
• divide_by_zero = 7 / 0
• Error in Python can be of two types i.e. Syntax errors and Exceptions.
Errors are problems in a program due to which the program will stop
the execution. On the other hand, exceptions are raised when some
internal events occur which change the normal flow of the program.
Different types of exceptions in python:

• In Python, there are several built-in Python exceptions that can be raised when an error occurs
during the execution of a program. Here are some of the most common types of exceptions in
Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the code,
such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• TypeError: This exception is raised when an operation or function is applied to an object of the
wrong type, such as adding a string to an integer.
• NameError: This exception is raised when a variable or function name is not found in the current
scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
• KeyError: This exception is raised when a key is not found in a dictionary.
• ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
• AttributeError: This exception is raised when an attribute or method is not found on an object,
such as trying to access a non-existent attribute of a class instance.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by zero.
• ImportError: This exception is raised when an import statement fails to find or load a module.
• A syntax error in the code :
• amount = 10000
• if(amount > 2999)
• print("You are eligible to purchase Dsa Self Paced")
• ZeroDivisionError:
marks = 10000
a = marks / 0
print(a)
Try and Except Statement – Catching Exceptions:
Try and except statements are used to catch and handle exceptions in Python. Statements that
can raise exceptions are kept inside the try clause and the statements that handle the exception
are written inside except clause.
• Example: Here we are trying to access the array element whose index is out of bound and
handle the corresponding exception.

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")
• try:
• numerator = 10
• denominator = 0

• result = numerator/denominator

• print(result)
• except:
• print("Error: Denominator cannot be 0.")

• # Output: Error: Denominator cannot be 0.


• try:

• even_numbers = [2,4,6,8]
• print(even_numbers[5])

• except ZeroDivisionError:
• print("Denominator cannot be 0.")

• except IndexError:
• print("Index Out of Bound.")

• # Output: Index Out of Bound


finally in Python
• The finally block always executes after normal termination of try
block or after try block terminates due to some exception.
Syntax:
• try:
• # Some Code....

• except:
• # optional block
• # Handling of exception (if required)

• finally:
• # Some code .....(always executed)
• # try block
• try:
• a = 10
• b=0
• print("Result of Division: " + str(a/b))
• except IndexError:
• print("Index Out of Bound.")
• except(ZeroDivisionError):
• print("Result of Division: ")

• finally:
• print("Code execution Wrap up!")
Handling FileNotFoundError Exception:
• ‘FileNotFoundError’ is a checked exception in Python and exception
handling should be done by making use of ‘try’ and ‘except’ block.
• Example: Here we have used try and except block to handle the error.

• try:
• file1 = open("Myfolder/abc.txt")

• except:
• print("file not found")
Exception handling with try, except, else, and finally

• Try: This block will test the excepted error to occur


• Except: Here you can handle the error
• Else: If there is no exception then this block will be executed
• Finally: Finally block always gets executed either exception is
generated or not
• # Python code to illustrate
• # working of try()
• def divide(x, y):
• try:
• # Floor Division : Gives only Fractional
• result = x // y
• except ZeroDivisionError:
• print("Sorry ! You are dividing by zero ")
• else:
• print("Yeah ! Your answer is :", result)
• finally:
• print('This is always executed')

• divide(3, 2)
• divide(3, 0)

You might also like