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

PYTHON UNIT-3

This document covers file handling and exception handling in Python, detailing how to open, read, write, and close files, as well as the different modes for file operations. It also explains exceptions, their types, and how to handle them using try and except blocks to ensure graceful error management during program execution. Key concepts include file paths, reading and writing methods, and the importance of proper file closure to prevent resource leaks.

Uploaded by

dhirishathinad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PYTHON UNIT-3

This document covers file handling and exception handling in Python, detailing how to open, read, write, and close files, as well as the different modes for file operations. It also explains exceptions, their types, and how to handle them using try and except blocks to ensure graceful error management during program execution. Key concepts include file paths, reading and writing methods, and the importance of proper file closure to prevent resource leaks.

Uploaded by

dhirishathinad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

MC4103_Python Programming Unit -3| File Handling And Exception Handling

Unit- III | FILE HANDLING AND EXCEPTION HANDLING


Files: Introduction – File Path – Opening and Closing Files – Reading and Writing
Files –File Position – Exception: Errors and Exceptions, Exception Handling, Multiple
Exceptions.

3.1 Files: Introduction

Files are named locations on disk to store related information. They are used to
permanently store data 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), we use
files for future use of the data by permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are
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
3.2 File Path

Absolute path
Always contains the root and the complete directory list to specify the exact
location of the file

Relative Path
Is specified relative to the program’s current working directory

3.3 Opening Files in Python

Python has a built-in open() function to open a file. This function returns a file object,
also called a handle, as it is used to read or modify the file accordingly.

Syntax of Python open file function


file_object = open("filename", "mode")
We can specify the mode while opening a file.

In mode, we specify whether we want to read r, write w or append a to the file. We


can also specify if we want to open the file in text mode or binary mode. The default is
reading in text mode.

In this mode, we get strings when reading from the file. On the other hand, binary
mode returns bytes and this is the mode to be used when dealing with non-text files like
images or executable files.

AVCCE/MCA/R-21/I-SEM/NS Page 1
MC4103_Python Programming Unit -3| File Handling And Exception Handling

f = open("test.txt") # open file in current directory


f = open("C:/Python34/README.txt") # specifying full path
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode

Mode Description

r Opens a file for reading. (default)

Opens a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.

x Opens a file for exclusive creation. If the file already exists, the operation fails.

Opens a file for appending at the end of the file without truncating it. Creates a new
a
file if it does not exist.

t Opens in text mode. (default)

b Opens in binary mode.

+ Opens a file for updating (reading and writing)

# Python code to illustrate read() mode


file = open("file.text", "r")
print (file.read())

# Python code to illustrate read() mode character wise


file = open("file.txt", "r")
print (file.read(5))

# Python code to create a file


file = open(‘test.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()

# Python code to illustrate append() mode


file = open(‘test.txt','a')
file.write("This will add this line")
file.close()

The character a does not imply the number 97 until it is encoded using ASCII (or other
equivalent encodings). the default encoding is platform dependent. In windows, it
is cp1252 but utf-8 in Linux.
So, we must not also rely on the default encoding or else our code will behave differently in
different platforms.

AVCCE/MCA/R-21/I-SEM/NS Page 2
MC4103_Python Programming Unit -3| File Handling And Exception Handling

Hence, when working with files in text mode, it is highly recommended to specify the
encoding type.
f = open("test.txt", mode='r', encoding='utf-8')

3.4 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 available in Python. Python has a garbage collector to clean up unreferenced
objects but we must not rely on it to close the file.
f = open("test.txt", encoding = 'utf-8') # perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file. A safer way is to use
a try...finally block.

3.4.1 try...finally

try:
f = open("test.txt", encoding = 'utf-8') # perform file operations
finally:
f.close()
This way, we are guaranteeing that the file is properly closed even if an exception is raised
that causes program flow to stop. The best way to close a file is by using the with statement. This
ensures that the file is closed when the block inside the with statement is existed. We don't need to
explicitly call the close() method. It is done internally.

with open("test.txt", encoding = 'utf-8') as f: # perform file operations

3.5 Reading and Writing Files

3.5.1 Writing to Files in Python


In order to write into a file in Python, we need to open it in write w, append a or exclusive
creation x mode.We need to be careful with the w mode, as it will overwrite into the file if it
already exists. Due to this, all the previous data are erased.

Writing a string or sequence of bytes (for binary files) is done using the write() method.
This method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
This program will create a new file named test.txt in the current directory if it does not exist.
If it does exist, it is overwritten. We must include the newline characters ourselves to distinguish
the different lines.

AVCCE/MCA/R-21/I-SEM/NS Page 3
MC4103_Python Programming Unit -3| File Handling And Exception Handling

3.5.2 Reading Files in Python


To read a file in Python, we must open the file in reading r mode. There are various
methods available for this purpose. We can use the read(size) method to read in the size number
of data.
If the size parameter is not specified, it reads and returns up to the end of the file. We can
read the test.txt file we wrote in the above section in the following way:
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
'This'
>>> f.read(4) # read the next 4 data
' is '
>>> f.read() # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'
>>> f.read() # further reading returns empty sting
''We can see that the read() method returns a newline as '\n'. Once the end of the file is
reached, we get an empty string on further reading. We can change our current file cursor
(position) using the seek() method. Similarly, the tell() method returns our current position (in
number of bytes).
>>> f.tell() # get the current file position
56
>>> f.seek(0) # bring file cursor to initial position
0
>>> print(f.read()) # read the entire file
This is my first file This file contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.
f = open("test.txt",'r',encoding = 'utf-8')
>>> for line in f:
print(line, end = '')
This is my first file
This file
contains three lines
In this program, the lines in the file itself include a newline character \n. So, we use the
end parameter of the print() function to avoid two newlines when printing. Alternatively, we can
use the readline() method to read individual lines of a file. This method reads a file till the
newline, including the newline character.
>>> f.readline() 'This is my first file\n'
>>> f.readline() 'This file\n'
>>> f.readline() 'contains three lines\n'
>>> f.readline()
''Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
methods return empty values when the end of file (EOF) is reached.
>>> f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n']

AVCCE/MCA/R-21/I-SEM/NS Page 4
MC4103_Python Programming Unit -3| File Handling And Exception Handling

3.6 Python File Methods

Method Description
close() Closes an opened file. It has no effect if the file is already closed.
Separates the underlying binary buffer from the TextIOBase and
detach()
returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
Reads at most n characters from the file. Reads till end of file if it is
read(n)
negative or None.
readable() Returns True if the file stream can be read from.
Reads and returns one line from the file. Reads in at most n bytes if
readline(n=-1)
specified.
Reads and returns a list of lines from the file. Reads in at most n
readlines(n=-1)
bytes/characters if specified.
Changes the file position to offset bytes, in reference to from (start,
seek(offset,from=SEEK_SET)
current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
Resizes the file stream to size bytes. If size is not specified, resizes to
truncate(size=None)
current location.
writable() Returns True if the file stream can be written to.
Writes the string s to the file and returns the number of characters
write(s)
written.
writelines(lines) Writes a list of lines to the file.

3.7 Exception: Errors and Exceptions,

The program that we write may behave abnormal or unexpectedly because of some errors
and exceptions. An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception.

An exception is a Python object that represents an error. When a Python script raises an
exception, it must either handle the exception immediately otherwise it terminates and quits.

3.7.1 Types of Errors

Basically, there are two types of errors:

AVCCE/MCA/R-21/I-SEM/NS Page 5
MC4103_Python Programming Unit -3| File Handling And Exception Handling

– Syntax errors- it occur due to poor understanding of the language. Or violate the rules of
python
>>> i=0
>>> if i==0 print(i)
SyntaxError: invalid syntax

– Logic errors- it occur due to poor understanding of the problem and its solutions. It leads
to run-time a error, that causes the program to terminate abruptly. The following are some
examples of runtime errors.

Example 1: Division by a zero


>>> 2/0
Traceback (most recent call last):
File , line 1, in <module>
ZeroDivisionError: division by zero

Example 2: Adding string to an integer.


>>> 10 + "12"
Traceback (most recent call last):
File , line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Example 3: Trying to access element at invalid index.


>>> list1 = [11, 3, 99, 15]
>>> list1[10]
Traceback (most recent call last):
File , line 1, in <module>
IndexError: list index out of range

Example 4: Opening a file in read mode which doesn't exist.


>>> f = open ("filedoesntexists.txt", "r")
Traceback (most recent call last):
File , line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'filedoesntexists.txt

3.8 Exceptions :

Exceptions are run-time anomalies or unusual conditions that a program may encounter
during the execution. (such as divide by zero, accessing arrays out of its bounds, running out of
memory or disk space, overflow, and underflow)

• Synchronous Exceptions – it can be controlled by the program.

• Asynchronous Exceptions – caused by the events that are beyond the control of the
program.

AVCCE/MCA/R-21/I-SEM/NS Page 6
MC4103_Python Programming Unit -3| File Handling And Exception Handling

Other Exceptions in python

• IO Error-If the file cannot be opened.


• Import Error -If python cannot find the module
• Value Error -Raised when a built-in operation or function receives an argument that has
the right type but an inappropriate value
• Keyboard Interrupt -Raised when the user hits the interrupt
• EOF Error -Raised when one of the built-in functions (input() or raw_input()) hits an
end-of-file condition (EOF) without reading any data

3.8.1 Exception Handling,

Exception handling is a mechanism which allows us to handle errors gracefully while the
program is running instead of abruptly ending the program execution. We can handle exceptions
in our program by using try block and except block. A critical operation which can raise
exceptions is placed inside the try block. The code that handles exceptions is written in except
block. Its syntax is as follows:

try:
# try block
# write code that might raise an exception here
<statement_1>
<statement_2>
except ExceptiomType:
# except block
# handle exception here
<handler>

Syntax for handling Exceptions

try:
write code here
except Exception1:
if exception1 occurs then execute this code
except Exception2:
if exception2 occurs then execute this code
….
….
else:
if there is no exception then execute this code

AVCCE/MCA/R-21/I-SEM/NS Page 7
MC4103_Python Programming Unit -3| File Handling And Exception Handling

3.8.2 Exception Handling Mechanism

3.8.2.1. Try –except: The try and except statements are used to handle runtime errors
Syntax:
try:
statements
except :
statements

The try statement works as follows:-


• First, the try clause (the statement(s) between the try and except keywords) is
executed.
• If no exception occurs, the except clause is skipped and execution of the try statement
is finished.
• If an exception occurs during execution of the try clause, the rest of the clause is
skipped.
• Then if its type matches the exception named after the except keyword, the except
clause is executed, and then execution continues after the try statement.

Example Program to handle the divide by zero exception

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

3.8.2.2. Try - multiple except: Try–Multiple except Statements


Syntax:
try:
statements
except errors1:
statements
except errors2:
statements
except errors3:
statements

AVCCE/MCA/R-21/I-SEM/NS Page 8
MC4103_Python Programming Unit -3| File Handling And Exception Handling

Example
X=int(input("Enter the value of X"))
Y=int(input("Enter the value of Y"))
try:
sum= X + Y
divide = X / Y
print ("Sum of {} and {} ={}".format(X,Y,sum))
print ("Division of {} and {} = {}".format(X,Y,divide))
except NameError:
print("The input must be number")
except ZeroDivisionError:
print("Division by Zero")
Output:
Enter the value of X 6
Enter the value of Y0
Division by Zero

3.8.2.3 .try -except-else

• The else part will be executed only if the try block does not raise the exception.
• Python will try to process all the statements inside try block.
• If value error occur, the flow of control will immediately pass to the except block and
remaining statements in try block will be skipped.

Syntax:
try:
statements
except:
statements
else:
statements

3.8.3 Multiple Exceptions

Try- Multiple except statements Division of 2 numbers


try:
a=int(input(“Enter value of a:”))
b=int(input(“Enter value of b:”))
c=a/b
except ValueError:

AVCCE/MCA/R-21/I-SEM/NS Page 9
MC4103_Python Programming Unit -3| File Handling And Exception Handling

print(“U have entered wrong data”)


except ZeroDivision Error:
print(“Divide by zero error”)
else:
print(“Result is”c)
Output:
Enter value of a:10
Enter value of b:a
U have entered wrong data

3.8.3.1 Raise statement


• The raise statement allows the programmer to force a specified exception to occur.
Syntax:
raise NameError('HiThere')
• If you need to determine whether an exception was raised but don’t intend to handle it, a
simpler form of the raise statement allows you to re-raise the exception.
x = -1
if x < 0:
raise Exception("No numbers below zero")
else:
print("Positive Number")
Output:
Exception: No numbers below zero

3.8.3.2. Try -except-finally

• Whether the exception is raised or not, finally block needs to be executed.


• The finally clause is also executed “on the way out” when any other clause of the try
statement is left via a break, continue or return statement.

Syntax:
try:
statements
except:
statements
finally:
statements

AVCCE/MCA/R-21/I-SEM/NS Page 10
MC4103_Python Programming Unit -3| File Handling And Exception Handling

Example
x=int(input("Enter the value of X"))
y=int(input("Enter the value of Y"))
try:
result=x/(x-y)
except ZeroDivisionError:
print("Division by Zero")
else:
print("result=",result)
finally:
print ("Program completed")

Enter the value of X 3


Enter the value of Y 6
result= -1.0
Program completed

File Not Found Error

#Read contents of file


try:
inFile=open(‘g.txt’,’r+’)
except IOError:
print(“Error:File not found”)
else:
print(inFile.read())
Output:
Error:File not found

***** SUCCESS!*****

AVCCE/MCA/R-21/I-SEM/NS Page 11

You might also like