File handling and Exception handling
File handling and Exception handling
Files are named locations on disk to store related information. They are used to store data
permanently in a non-volatile memory (e.g. hard disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the computer is
turned off), files are used for future use of the data by permanently storing them.
To read from or write to a file, it needs to be opened first. When operation is done, it needs to
be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
Open a file
Read or write (perform operation)
Close the file
Absolute path
An absolute path is defined as specifying the location of a file or directory from the root
directory(/).
In other words, an absolute path is a complete path from start of actual file system from /
directory.
Relative path
Relative path is defined as the path related to the current working directly(cwd). It starts at
your current directory and never starts with a / .
Opening a file
The key function for working with files in Python is the open() function.
The open() function takes two parameters filename mode.
Syntax To open a file for reading it is enough to specify the name of the file:
f = open(“Myfile.txt")
The code above is the same as:
f = open(“Myfile.txt", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists in cwd, or else you will get an error.
Closing a file
It is a good practice to always close the file when you are done with it.
Syntax
f = open(“Myfile.txt", "r")
f.close()
Note: You should always close your files, in some cases, due to buffering, changes made to a
file may not show until you close the file.
Reading file
The open() function returns a file object, which has a read() method for reading the content of
the file:
Syntax
f = open(“Myfile.txt", "r")
print(f.read())
f.close()
In [3]:
help(f.read)
In [20]:
f =open("myfile.txt", "rt")
print(f.read())
f.close()
hello
how are you
thank you
In [21]:
# By default, the read() method returns the whole text,
# but you can also specify how many characters you want to read
f =open("myfile.txt")
print(f.read(5))
f.close()
hello
In [3]:
help(f.readline)
In [61]:
f =open("myfile.txt", "r")
print(f.readline())
hello
thank you
In [23]:
f =open("myfile.txt", "r")
print(f.readline())
print(f.readline())
f.close()
hello
In [4]:
help(f.readlines)
In [59]:
f =open("myfile.txt", "r")
print(f.readlines(17))
f.close()
hello
thank you
Writing on file
In [5]:
help(f.write)
write() method does not add a newline(‘\n’) character to the end of string.
In [1]:
# writing content on a file
text=input("Enter the content of the file:")
f=open("mywrite.txt","wt")
f.write(text)
f.close()
f=open("mywrite.txt","rt")
print(f.read())
f.close()
In [11]:
#Create a file called "myfilex.txt":
f = open("myfilex.txt", "x")
In [2]:
#Open the file “mywrite.txt" and append content to the file:
f = open("mywrite.txt", "a")
f.write(" Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("mywrite.txt", "r")
print(f.read())
File Handling and exception handling Now the file has more content!
In [29]:
#Open the file "mywrite.txt" and overwrite the content:
f = open("mywrite.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("mywrite.txt", "r")
print(f.read())
In [16]:
help(f.writelines)
In [33]:
#Program to write a file using writelines() method
file=open("mydemo.txt","wt")
lines=["Hello world\n", "Welcome to python\n", "Enjoy Python"]
file.writelines(lines)
file.close()
print("Data written to file")
file=open("mydemo.txt","rt")
print(file.read())
In [5]:
# use of split in file handling
f=open("mydemo.txt","rt")
data=f.readlines()
print(data)
for line in data:
word=line.split()
print(data)
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9668/3631648392.py in <module>
1 # use of split in file handling
----> 2 f=open("mydemo.txt","rt")
3 data=f.readlines()
4 print(data)
5 for line in data:
In [35]:
s=input("enter the content of file: ")
f=open("myfile7.txt","wt")
f.write(s)
f.close()
f1=open("myfile7.txt","rt")
f2=open("myfile8.txt","wt")
st=f1.read()
f2.write(st)
f2.close()
f1.close()
f2=open("myfile8.txt","rt")
localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 6/17
2/18/22, 2:55 PM File handling and Exception handling
print(f2.read())
f2.close()
enter the content of file: python programming language is very easy to learn.
python programming language is very easy to learn.
1. A file named DATA contains a series of integer numbers. Write a program to read these
numbers and then write all "odd" numbers to a file to be called ODD and all "even" numbers to
a file to be called EVEN.
In [37]:
i=input("Enter space seperated numbers : ")
f=open("data.txt","w")
f.write(i)
f.close()
f=open("data.txt","r")
c=f.read()
print("content of original file:",c)
f.close()
d=c.split()
e=open("even.txt","w")
o=open("odd.txt","w")
for i in range(0,len(d)):
g=int(d[i])
if g%2==0:
e.write(d[i]+" ")
else:
o.write(d[i]+" ")
e.close()
o.close()
e=open("even.txt","r")
o=open("odd.txt","r")
print("content of even file:",e.read())
print("content of odd file:",o.read())
1. WAP to count the number of occurrences of vowel and consonants in the file.
In [10]:
s=input("enter the content of file ")
f=open("myfile4.txt","wt")
print(f.write(s))
f.close()
f=open("myfile4.txt","rt")
data=f.read()
f.close()
countv=0
countc=0
for x in data:
if x in "aeiouAEIOU":
countv=countv+1
elif 'a'<=x<='z' or 'A'<=x<='Z':
countc=countc+1
else:
pass
print("no. of vowels=",countv)
print("no. of conso=",countc)
1. WAP to count the number of words, characters and lines in the file
In [41]:
f=open("hello.txt","w")
f.write("hello\nhow are you\ni am fine\nthankyou")
f.close()
f=open("hello.txt","r")
d=f.read()
print(d)
print("no of characters=",len(d))
j=d.split()
print("no of words",len(j))
f.seek(0)
x=f.readlines()
print("no of lines=",len(x))
f.close()
hello
how are you
i am fine
thankyou
no of characters= 36
no of words 8
no of lines= 4
The tell() method returns the current file position in a file stream.
The seek() method sets the current file position in a file stream. The seek() method also returns
the new postion.
In [68]:
f = open("mydemo.txt", "r")
print(f.read())
f.seek(4)
print(f.readline())
Hello world
Welcome to python
Enjoy Python
o world
In [69]:
f = open("mydemo.txt", "r")
print(f.readline())
print(f.tell())
print(f.read())
Hello world
13
Welcome to python
Enjoy Python
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Exception Handling
Certain mistakes may be made while writing a program that led to errors when we try to run it.
A python program terminates as soon as it encounters an unhandled error.
These errors can be broadly classified into two classes:
Syntax errors
Logical errors (Exceptions)
Syntax Error
Error caused by not following the proper structure (syntax) of the language is called syntax
error or parsing error.
Syntax errors are the most basic type of error. They arise when the Python parser is unable to
understand a line of code.
Examples
In [ ]:
# SyntaxError: can't assign to literal
2=x
In [ ]:
x=2
if x==2 # SyntaxError: invalid syntax
print('yes')
In [ ]:
# SyntaxError: Missing parentheses in call to 'print'.
print x
In [ ]:
a = int(input('Enter a ')
b = 23
s = a + b
print(s)
Logical Errors
localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 10/17
2/18/22, 2:55 PM File handling and Exception handling
Errors that occur at runtime (after passing the syntax test) are called exceptions or logical errors.
These are the most difficult type of error to find, because they will give unpredictable results
and may crash your program.
Whenever these types of runtime errors occur, Python creates an exception object.
If not handled properly, it prints a trace back to that error along with some details about why
that error occurred.
In [ ]:
print(dir(__builtins__))
Value Error
import math
f=math.factorial(-5)
print(f)
ValueError: factorial() not defined for negative values
NameError
print(x)
NameError: name 'x' is not defined
Type Error
x=5+'c'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Indentation Error
x,y=2,3
if x==0:
print(x)
else:
print(y)
IndentationError: expected an indented block
import Error
import ab
ModuleNotFoundError: No module named 'ab'
Index Error
list1=[1,2,3]
list1[3]=4
IndexError: list assignment index out of range
Exception Handling
Python provides two very important features to handle any unexpected error in your Python
programs and to add debugging capabilities in them.
Exception Handling
Assertions
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.
When a Python encounters a situation that it cannot cope with, it raises an exception. An
exception is a Python object that represents an error.
When Python raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
Handling Exception
We can handle exceptions in our program by using try block and except block.
A critical operation which can raise exception is placed inside the try block and the code that
handles exception is written in except block.
Syntax:
try:
statements
except ExceptionName:
statements
In [ ]:
num=int(input('Enter the numerator : '))
deno=int(input('Enter the denominator : '))
try:
quo=num/deno
print('Quotient : ',quo)
except ZeroDivisionError:
print('Denominator cannot be zero')
Multiple Exception
Python allows you to have multiple except blocks for a single try block.
The block which matches with the exception generated will get executed.
A try block can be associated with more than one except block to specify handlers for different
exceptions.
Exception handlers only handle exceptions that occur in the corresponding try block.
The syntax for specifying multiple except blocks for a single try block can be given as,
localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 13/17
2/18/22, 2:55 PM File handling and Exception handling
In [ ]:
try:
num=int(input(“Enter the number : ”))
print(num**2)
except KeyboardInterrupt:
print('You should have entered a number…..Program Terminating….')
except ValueError:
print('Please check before you enter ….. Program Terminating ….'')
print('Bye')
In [ ]:
try:
num = int(input('Enter the number : '))
print(num**2)
except (KeyboardInterrupt, ValueError, TypeError):
print('Please check before you enter….Program terminating….')
print('Bye”)
else Clause
The try ... except block can optionally have an else clause, which, when present, must follow all
except blocks.
The statement(s) in the else block is executed only if the try clause does not raise an exception.
else Clause
In [ ]:
try:
file = open('file.txt')
str = file.readline()
print(str)
except IOError:
print('Error occurred during Input…….Program Terminating……')
else:
print('Program Terminating Successfully……')
finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
In [ ]: try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Raise an exception
As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword.
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
In [2]:
def MyError(s):
try:
print(s)
except TypeError:
print(s)
# raise TypeError(s)
x = 'hello'
if not type(x) is int:
raise MyError("Only integers are allowed")
Python Assert
Python assert keyword is defined as a debugging tool that tests a condition.
The Assertions are mainly the assumption that state a fact confidently in the program.
For example, while writing a division function, the divisor should not be zero, and you assert
that divisor is not equal to zero.
It is simply a boolean expression that has a condition or expression checks if the condition
returns true or false.
If it is true, the program does not do anything, and it moves to the next line of code.
But if it is false, it raises an AssertionError exception with an optional error message.
Syntax-
In [ ]:
# Example
def avg(scores):
assert len(scores) != 0,"The List is empty."
return sum(scores)/len(scores)
scores2 = [67,59,86,75,92]
print("The Average of scores2:",avg(scores2))
scores1 = []
print("The Average of scores1:",avg(scores1))
In [ ]: