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

File handling and Exception handling

This document covers file and exception handling in Python, detailing the process of opening, reading, writing, and closing files, as well as the types of files (text and binary) that can be handled. It also explains the concepts of absolute and relative paths, various file operations, and the importance of exception handling to manage errors in code execution. Additionally, it provides examples of common file operations and error types, including syntax and logical errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

File handling and Exception handling

This document covers file and exception handling in Python, detailing the process of opening, reading, writing, and closing files, as well as the types of files (text and binary) that can be handled. It also explains the concepts of absolute and relative paths, various file operations, and the importance of exception handling to manage errors in code execution. Additionally, it provides examples of common file operations and error types, including syntax and logical errors.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

2/18/22, 2:55 PM File handling and Exception handling

UNIT-V: File and Exception handling


Files and Directories: Introduction to File Handling, Reading and Writing files, Additional file
methods,
Working with Directories.
Exception Handling, Errors, Run Time Errors, Handling I/O Exception, Try-except statement,
Raise, Assert.

FILE HANDLING IN PYTHON

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

Relative path and absolute path

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 / .

Types of files that can be handled in python


Python provides inbuilt functions for creating, writing and reading files.
There are two types of files that can be handled in python:
Normal text files
Binary files (written in binary language,0s and 1s).
Text files:
In this type of file, Each line of text is terminated with a special character called EOL (End of
Line), which is the new line character (‘\n’) in python by default.
Binary files:
In this type of file, there is no terminator for a line and the data is stored after converting it
into machine understandable binary language.
localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 1/17
2/18/22, 2:55 PM File handling and Exception handling

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.

File Opening Modes

File Access Mode

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")

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 2/17


2/18/22, 2:55 PM File handling and Exception handling

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)

Help on built-in function read:

read(size=-1, /) method of _io.TextIOWrapper instance


Read at most n characters from stream.

Read from underlying buffer until we have n characters or we hit EOF.


If n is negative or omitted, read until EOF.

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)

Help on built-in function readline:

readline(size=-1, /) method of _io.TextIOWrapper instance


Read until newline or EOF.

Returns an empty string if EOF is hit immediately.

In [61]:
f =open("myfile.txt", "r")
print(f.readline())

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 3/17


2/18/22, 2:55 PM File handling and Exception handling
f.close()

hello

how are you

thank you

In [23]:
f =open("myfile.txt", "r")
print(f.readline())
print(f.readline())
f.close()

hello

how are you

In [4]:
help(f.readlines)

Help on built-in function readlines:

readlines(hint=-1, /) method of _io.TextIOWrapper instance


Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more


lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.

In [59]:
f =open("myfile.txt", "r")
print(f.readlines(17))
f.close()

['hello\n', 'how are you\n']

Looping Through File


In [25]:
# By looping through the file,
# you can read the whole file, line by line:
f = open("myfile.txt", "r")
for x in f:
print(x)

hello

how are you

thank you

Writing on file
In [5]:
help(f.write)

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 4/17


2/18/22, 2:55 PM File handling and Exception handling
Help on built-in function write:

write(text, /) method of _io.TextIOWrapper instance


Write string to stream.
Returns the number of characters written (which is always equal to
the length of the string).

write() method is used to write a string to an already opened file.

Strings may include numbers, special characters or other symbols.

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()

Enter the content of the file:File Handling and exception handling


File Handling and exception handling

In [11]:
#Create a file called "myfilex.txt":
f = open("myfilex.txt", "x")

#Create a new file myfilew.txt if it does not exist:


f = open("myfilew.txt", "w")

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())

Woops! I have deleted the content!

In [16]:
help(f.writelines)

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 5/17


2/18/22, 2:55 PM File handling and Exception handling
Help on built-in function writelines:

writelines(lines, /) method of _io.TextIOWrapper instance


Write a list of lines to stream.

Line separators are not added, so it is usual for each of the


lines provided to have a line separator at the end.

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())

Data written to file


Hello world
Welcome to python
Enjoy Python

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:

FileNotFoundError: [Errno 2] No such file or directory: 'mydemo.txt'

File Handling Programs

1. Copy the content of one file onto another file

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())

Enter space seperated numbers : 10 15 20 22 25


content of original file: 10 15 20 22 25
content of even file: 10 20 22
content of odd file: 15 25

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:

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 7/17


2/18/22, 2:55 PM File handling and Exception handling

pass
print("no. of vowels=",countv)
print("no. of conso=",countc)

enter the content of fileHello Students! Good Morning


28
no. of vowels= 8
no. of conso= 16

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

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 8/17


2/18/22, 2:55 PM File handling and Exception handling

13
Welcome to python
Enjoy Python

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

In [ ]:

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 9/17


2/18/22, 2:55 PM File handling and Exception handling

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.

Logical Errors can be of two types:


First is caused by a mistake in the program's logic. You won't get an error message,
because no syntax or runtime error has occurred. They occur when the program runs
without crashing but produces an incorrect result.
Second are caused by Illegal operations that can raise exceptions.
There are plenty of built-in exceptions in Python that are raised when corresponding errors
occur
mWe can view all the built-in exceptions using the built-in locals() function as follows:
print(dir(locals()[' __builtins__ ']))

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

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 11/17


2/18/22, 2:55 PM File handling and Exception handling

Zero Division Error


a= 5/0
ZeroDivisionError: division by zero

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

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 12/17


2/18/22, 2:55 PM File handling and Exception handling

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”)

Except Bock without Exception


In [ ]:
try:
file = pen('File1.txt')
str=f.readline()
print(str)
except IOError:
print('Error occurred during Input ………Program Terminating…..')
except valueError:
print('Could not convert data to an integer.')
except:
print('Unexcepted error……Program Terminating…..')

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.

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 14/17


2/18/22, 2:55 PM File handling and Exception handling

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……')

List of some Standard Exceptions

finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 15/17


2/18/22, 2:55 PM File handling and Exception handling

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")

Only integers are allowed


---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-dccbec25576d> in <module>
7 x = 'hello'
8 if not type(x) is int:
----> 9 raise MyError("Only integers are allowed")

TypeError: exceptions must derive from BaseException

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.

Why Assertion is used

It is a debugging tool, and its primary task is to check the condition.


If it finds that condition is true, it moves to the next line of code, and If not then stops all its
operations and throws an error.

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 16/17


2/18/22, 2:55 PM File handling and Exception handling

It points out the error in the code.

Where Assertion in Python used

Checking the outputs of the functions.


Used for testing the code.
In checking the values of arguments.
Checking the valid input.

Syntax-

assert condition, error_message(optional)

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 [ ]:

localhost:8888/nbconvert/html/File handling and Exception handling.ipynb?download=false 17/17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy