Unit III File Handling and Exception Handling
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
demofile.txt
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.
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()
"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")
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
line = fo.readline()
print "Read Line: %s" % (line)
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:
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:
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.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
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.
try:
fun(3)
fun(5)
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
Output:
-5.0
a/b result in 0
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
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).
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