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

Unit III File Handling and Exception Handling

This document provides an overview of file handling and exception handling in Python. It explains how to open, read, write, and delete files, as well as the various modes for file operations and methods available for file objects. Additionally, it covers the concepts of exceptions, including syntax errors, try-except statements, and raising exceptions.
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)
5 views

Unit III File Handling and Exception Handling

This document provides an overview of file handling and exception handling in Python. It explains how to open, read, write, and delete files, as well as the various modes for file operations and methods available for file objects. Additionally, it covers the concepts of exceptions, including syntax errors, try-except statements, and raising exceptions.
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/ 16

UNIT III FILE HANDLING AND EXCEPTION HANDLING

Files
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:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Working of open() function
Before performing any operation on the file like reading or writing, first, we have to open that
file. For this, we should use Python’s inbuilt function open() but at the time of opening, we
have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data then it
will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
7. In addition you can specify if the file should be handled as binary or text mode
8. "t" - Text - Default value. Text mode
9. "b" - Binary - Binary mode (e.g. images)

f = open("demofile.txt", "rt")
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

Open a File on the Server


Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the
file:

Example
f = open("demofile.txt", "r")
print(f.read())
If the file is located in a different location, you will have to specify the file path, like this:

Example
Open a file on a different location:

f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
Return the 5 first characters of the file:

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

Read Lines
You can return one line by using the readline() method:

Example
Read one line of the file:

f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:

Example
Read two lines of the file:

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
By looping through the lines of the file, you can read the whole file, line by line:

Example
Loop through the file line by line:

f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.

Example
Close the file when you are finish with it:

f = open("demofile.txt", "r")
print(f.readline())
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.

Python File Write


Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example
Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()

#open and read the file after the appending:


f = open("demofile3.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.

Create a New File


To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "myfile.txt":

f = open("myfile.txt", "x")
Result: a new empty file is created!

Example
Create a new file if it does not exist:

f = open("myfile.txt", "w")
split() using file handling
We can also split lines using file handling in Python. This splits the variable when space is
encountered. You can also split using any characters as we wish. Here is the code:
# Python code to illustrate split() function
with open("file.text", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)

Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:

Example
Remove the file "demofile.txt":

import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete it:

Example
Check if file exists, then delete it:

import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":

import os
os.rmdir("myfolder")

Python File seek() Method – File Position


Python file method seek() sets the file's current position at the offset. The whence argument is
optional and defaults to 0, which means absolute file positioning, other values are 1 which means
seek relative to the current position and 2 means seek relative to the file's end.
There is no return value. Note that if the file is opened for appending using either 'a' or 'a+', any
seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is essentially a no-op,
but it remains useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other
offsets causes undefined behavior.
Note that not all file objects are seekable.
Syntax
Following is the syntax for seek() method −

fileObject.seek(offset[, whence])
Parameters
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file positioning, other values
are 1 which means seek relative to the current position and 2 means seek relative to the file's end.

Return Value
This method does not return any value.

Example
The following example shows the usage of seek() method.
Python is a great language
Python is a great language
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

# Assuming file has following 5 lines


# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.readline()
print "Read Line: %s" % (line)

# Again set the pointer to the beginning


fo.seek(0, 0)
line = fo.readline()
print "Read Line: %s" % (line)

# Close opend file


fo.close()
When we run above program, it produces following result −

Name of the file: foo.txt


Read Line: Python is a great language.
Read Line: Python is a great language.
Python File Methods
There are various methods available with the file object. Some of them have been used in the
above examples.
Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and 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.
read(n) Reads at most n characters from the file. Reads till end of file if it is negative
or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if
specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n
bytes/characters if specified.
seek(offset,from=SEEK_ Changes the file position to offset bytes, in reference to from (start, current,
SET) end).
seekable() Returns True if the file stream supports random access.
tell() Returns an integer that represents the current position of the file's object.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current
location.
writable() Returns True if the file stream can be written to.
write(s) Writes the string s to the file and returns the number of characters written.
writelines(lines) Writes a list of lines to the file.

Exceptions
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the
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 changes the normal flow of the
program.
Difference between Syntax Error and Exceptions
Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It
leads to the termination of the program.
Example:

# initialize the amount variable


amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")

Output:

Exceptions: Exceptions are raised when the program is syntactically correct, but the code
resulted in an error. This error does not stop the execution of the program, however, it
changes the normal flow of the program.
Example:

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)

Output:
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Note: Exception is the base class for all the exceptions in Python. You can check the
exception hierarchy here.

 The try block lets you test a block of code for errors.
 The except block lets you handle the error.
 The else block lets you execute code when there is no error.
 The finally block lets you execute code, regardless of the result of the try- and except
blocks.

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: Let us try to access the array element whose index is out of bound and handle the
corresponding exception.

# Python program to handle simple runtime error


#Python 3

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

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

Output
Second element = 2
An error occurred

In the above example, the statements that can cause the error are placed inside the try
statement (second print statement in our case). The second print statement tries to access the
fourth element of the list which is not there and this throws an exception. This exception is
then caught by the except statement.

Catching Specific Exception


A try statement can have more than one except clause, to specify handlers for different
exceptions. Please note that at most one handler will be executed. For example, we can add
IndexError in the above code. The general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exception in Python

# Program to handle multiple errors with one


# except statement
# Python 3
def fun(a):
if a < 4:

# throws ZeroDivisionError for a = 3


b = a/(a-3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
fun(3)
fun(5)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of b, NameError
occurs.
Try with Else Clause
In python, you can also use the else clause on the try-except block which must be present
after all the except clauses. The code enters the else block only if the try clause does not
raise an exception.
Example: Try with else clause

# Program to depict else clause with try-except


# Python 3
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output:
-5.0
a/b result in 0

Finally Keyword in Python


Python provides a keyword finally, which is always executed after the try and except
blocks. The final 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)

else:
# execute if no exception

finally:
# Some code .....(always executed)
Example:

# Python program to demonstrate finally

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

Output:
Can't divide by zero
This is always executed
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole
argument in raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception).

# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not

The output of the above code will simply line printed as “An exception” but a Runtime error
will also occur in the last due to the raise statement in the last line. So, the output on your
command line will look like
Traceback (most recent call last):
File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>
raise NameError("Hi there") # Raise Error
NameError: Hi there

You might also like