Unit 3: Exceptions and Files
Unit 3: Exceptions and Files
file1 = open("test.txt")
# equivalent to 'r' or 'rt‘
file1 = open("test.txt",'w')
# write in text mode
file1 = open("img.bmp",'r+b')
# read and write in binary mode
Reading Files in Python
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read()
print(read_content)
Closing Files in Python
When we are done with performing operations on
the file, we need to properly close the file.
Closing a file will free up the resources that were
tied with the file. It is done using
the close() method in Python. For example,
# open a file
file1 = open("test.txt", "r")
# read the file
read_content = file1.read() print(read_content)
# close the file
file1.close()
Use of with...open Syntax
/Users/dannysteenman/projects/example-project/
src/lib/
Manipulating Pathnames
Example
The following program returns the directory name from the input
file path using the os.path.dirname() function −
import os
inputFilepath = 'C:/Users/cirus/Desktop/test.pdf'
print("Give Input Path is:",inputFilepath)
# getting the directory/folder path from the input file path using
dirname() function
print("Directory path of the given path is: ", os.path.dirname(inputFilepath))
Joining path components together
os.path.join() function
Python's os.path.join() function effectively joins one or
more path components. With the exception of the last
path component, this approach concatenates different
path components by placing exactly one directory
separator ('/') after each non-empty portion. A directory
separator ('/') is added at the end of the last path
component to be joined is empty.
All previously joined components are deleted if a path
component represents an absolute path, and joining
moves on from the absolute path component.
Example
The following program joins the given path components with
the base name using the os.path.join() function −
# importing os module
import os
# input path of the file
inputFilepath = 'C:/Users/cirus/Desktop/kohli.pdf‘
# Printing the given input path
print("Give Input Path is:",inputFilepath)
# joining the components to the main file name of
the input file path
print("Joining the given paths to input Path:\n",
os.path.join('tutorials', 'python',
os.path.basename(inputFilepath)))
Output
Give Input Path is: C:/Users/cirus/Desktop/kohli.pdf
Joining the given paths to input Path: tutorials/python/kohli.pdf
Splitting the file extension from file path:
import os
# input path of the file
inputFilepath ='C:/Users/cirus/Desktop/tutorial.pdf'
# Printing the given input path
print("Give Input Path is:",inputFilepath)
# splitting the file path and file extension from the input file
path
# using the splitext() function
print("Splitting the given path by extension :\n",os.path.splitext(inputFilepath))
Output
output −
import os
out = os.path.basename("/baz/foo")
print(out)
os.path.dirname(path) : It is used to return the
directory name from the path given. This function
returns the name from the path except the path name.
import os
out = os.path.dirname("/baz/foo")
print(out)
os.path.isabs(path) : It specifies whether the path is
absolute or not. In Unix system absolute path means path
begins with the slash(‘/’) and in Windows that it begins
with a (back)slash after chopping off a potential drive
letter.
import os
out = os.path.isabs("/baz/foo")
print(out)
os.path.isdir(path) : This function specifies whether
the path is existing directory or not.
import os
out = os.path.isdir("C:\\Users")
print(out)
os.path.isfile(path) : This function specifies whether
the path is existing file or not.
import os
out = os.path.isfile("C:\\Users\foo.csv")
print(out)
Getting file information
import os
file_path = "/Users/sabe/text.txt"
file_stats = os.stat(file_path)
print(file_stats)
These attributes include the file size, file owner id, file group
id, permissions, and more.
Traversing Directories and Processing Files
A common programming task is walking a directory
tree and processing files in the tree. Let’s explore
how the built-in Python function os.walk() can be
used to do this. os.walk() is used to generate
filename in a directory tree by walking the tree
either top-down or bottom-up.
import os
data_file = 'C:\\Users\\vuyisile\\Desktop\\Test\\data.txt'
os.remove(data_file)
Example:
# Open function to open the file "MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")
# store its reference in the variable file1
# and "MyFile2.txt" in D:\Text in file2
file2 = open(r"D:\Text\MyFile2.txt","w+")
Example :
# Opening and Closing a file "MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Appending to a file
Example
file = open('test.txt', 'rb') print(type(file))
# Output: <class '_io.BufferedReader'>
Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the
text file.
File_object.write(str1)
File_object.readlines()
Python has tools for working with binary files. Binary files
use strings of type bytes. This means when reading binary
data from a file, an object of type bytes is returned.
The binary file is opened using the open() function,
whose mode parameter contains the character ‘b’. More
details about opening/closing binary files are described
here.
Unlike text files, binary files do not convert characters to
the end of the string ‘\n’.
An example demonstrating the features of the
presentation of information in binary files.
# Open binary file for reading
f = open('myfile1.bin', 'rb')
# Get a string from binary file
d = f.read()
# Display this string.
# The output will be as a string of characters
print("d = ", d)
# d = b'\x80\x03]q\x00(K\x01\x88G@\x07\n=p\xa3\xd7\
ne.‘
# If print as a separate character, # then the character
code will be displayed - as an integer
print("d[5] = ", d[5]) # d[5] = 40
print("d[0] = ", d[0]) # d[0] = 128
# Use bin function for single character
print(bin(d[2])) # 0b1011101 f.close()
Output:
d = b'\x80\x03]q\x00(K\x01\x88G@\x07\n=p\xa3\xd7\ne.'
d[5] = 40
d[0] = 128
0b1011101
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
try with else clause
In some situations, we might want to run a certain block
of code if the code block inside try runs without any
errors.
For these cases, you can use the optional else keyword
with the try statement.
# program to print the reciprocal of even numbers
try:
num = int(input("Enter a number: "))
assert num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num print(reciprocal)
try...finally
In Python, the finally block is always executed no matter
whether there is an exception or not.
The finally block is optional. And, for each try block,
there can be only one finally block.
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.“)
The example below accepts two numbers from the user and performs
their division. It demonstrates the uses of else and finally blocks.
try:
print('try block')
x=int(input('Enter a number: '))
y=int(input('Enter another number: '))
z=x/y
except ZeroDivisionError:
print("except ZeroDivisionError block")
print("Division by 0 not accepted")
else:
print("else block")
print("Division = ", z)
finally:
print("finally block")
x=0
y=0
print ("Out of try, except, else and finally blocks." )
Raise an Exception
Python also provides the raise keyword to be used in the
context of exception handling. It causes an exception to be
generated explicitly. Built-in errors are raised implicitly.
However, a built-in or custom exception can be forced
during execution.
The following code accepts a number from the user. The
try block raises a ValueError exception if the number is
outside the allowed range.
try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")
x = "hello"
2. assert <expression>
Example
Here is a function that converts a temperature from degrees Kelvin
to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it
gets, the function bails out if it sees a negative temperature −
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
x = 10
assert x > 0
print('x is a positive number.')
Output
x is a positive number.
The assert statement can optionally include an error message
string, which gets displayed along with the AssertionError.
Consider the following assert statement with the error
message.
x=0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output
Traceback (most recent call last):
assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed
The following example uses the assert statement in the
function.
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
n = square(2) # returns 4
n = square(-2) # raise an AssertionError
The AssertionError is also a built-in exception that can be
handled using try-except construct as shown below:
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
try:
square(-2)
except AssertionError as msg:
print(msg)
Defining new exceptions :
class CustomException(Exception):
""" my custom exception class """
Example:
class CustomError(Exception):
pass
Output: CustomError:
Example of Custom Exceptions in Python
The Python Exception Class Hierarchy
BaseException
Exception
ArithmeticError
FloatingPointError
OverflowError
ZeroDivisionError
AssertionError
AttributeError
BufferError
EOFError
ImportError
ModuleNotFoundError
LookupError
IndexError
KeyError
MemoryError
NameError
UnboundLocalError
OSError
BlockingIOError
ChildProcessError
ConnectionError
BrokenPipeError
ConnectionAbortedErro
r
ConnectionRefusedErro
r
ConnectionResetError
FileExistsError
FileNotFoundError
InterruptedError
IsADirectoryError
NotADirectoryError
PermissionError
ProcessLookupError
TimeoutError
ReferenceError
RuntimeError
NotImplementedError
RecursionError
StopIteration
StopAsyncIteration
SyntaxError
IndentationError
TabError
SystemError
TypeError
ValueError
UnicodeError
UnicodeDecodeError
UnicodeEncodeError
UnicodeTranslateError
Warning
BytesWarning
DeprecationWarning
FutureWarning
ImportWarning
PendingDeprecationWa
rning
ResourceWarning
RuntimeWarning
SyntaxWarning
UnicodeWarning
UserWarning
GeneratorExit
KeyboardInterrupt
SystemExit
UNIT -3
COMPLETED