Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views47 pages

CO6I Unit6 - File IO Handling and Exception Handling

The document provides an overview of file input/output operations and exception handling in Python. It covers how to print to the screen, read keyboard input, open files in various modes, read and write files, and manage file pointers, as well as common exceptions and how to handle them using try-except blocks. Additionally, it discusses raising user-defined exceptions and the use of the os module for file management tasks.

Uploaded by

iqbalshaikh64684
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)
4 views47 pages

CO6I Unit6 - File IO Handling and Exception Handling

The document provides an overview of file input/output operations and exception handling in Python. It covers how to print to the screen, read keyboard input, open files in various modes, read and write files, and manage file pointers, as well as common exceptions and how to handle them using try-except blocks. Additionally, it discusses raising user-defined exceptions and the use of the os module for file management tasks.

Uploaded by

iqbalshaikh64684
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/ 47

FILE I/O

HANDLING AND
EXCEPTION
HANDLING
I/O OPERATIONS
1) PRINTING TO THE SCREEN
• The simplest way to produce output is using
the print statement where you can pass zero
or more expressions separated by commas.
• This function converts the expressions you
pass into a string and writes the result to
standard output.
• Example:
• print ("Python is really a great language,",
"isn't it?“)
2) READING KEYBOARD INPUT
• Python provides built-in function input to read
a line of text from standard input, which by
default comes from the keyboard.
• Example:
str = input("Enter your input: ")
print ("Received input is : ", str)
• raw_input does not interpret the input. It
always returns the input of the user without
changes, i.e. raw. Which is renamed to print
in python 3.
FILE HANDLING OPENING FILE
IN DIFFERENT MODES
• Before you can read or write a file, you have
to open it using Python's built-
in open() function.
• This function creates a file object, which
would be utilized to call other support
methods associated with it.
• Syntax:
file object = open(file_name [, access_mode]
[, buffering])

• file_name − The file_name argument is a


string value that contains the name of the file
that you want to access.
• access_mode − The access_mode
determines the mode in which the file has to
be opened, i.e., read, write, append, etc
• This is optional parameter and the default file
access mode is read (r).
• buffering −
• If the buffering value is set to 0, no buffering
takes place.
• If the buffering value is 1, line buffering is
performed while accessing a file.
• If you specify the buffering value as an
integer greater than 1, then buffering action
is performed with the indicated buffer size.
• If negative, the buffer size is the system
default(default behavior).
MODES OF OPENING A FILE
Sr Modes & Description
1 r : Opens a file for reading only. The file pointer is
placed at the beginning of the file. This is the
default mode.
2 rb : Opens a file for reading only in binary format.
The file pointer is placed at the beginning of the
file. This is the default mode.
3 r+ : Opens a file for both reading and writing. The
file pointer placed at the beginning of the file.
4 rb+ : Opens a file for both reading and writing in
binary format. The file pointer placed at the
beginning of the file.
5 w : Opens a file for writing only. Overwrites the
file if the file exists. If the file does not exist,
creates a new file for writing.
6 wb : Opens a file for writing only in binary format.
Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
7 w+ : Opens a file for both writing and reading.
Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading
and writing.
8 wb+ : Opens a file for both writing and reading in
binary format. Overwrites the existing file if the
file exists. If the file does not exist, creates a new
file for reading and writing.
9 a : Opens a file for appending. The file pointer is at
the end of the file if the file exists. If the file does not
exist, it creates a new file for writing.
10 ab : Opens a file for appending in binary format.
The file pointer is at the end of the file if the file
exists. If the file does not exist, it creates a new file
for writing.
11 a+ : Opens a file for both appending and reading.
The file pointer is at the end of the file if the file
exists. If the file does not exist, it creates a new file
for reading and writing.
12 ab+ : Opens a file for both appending and reading
in binary format. The file pointer is at the end of the
file if the file exists. If the file does not exist, it
creates a new file for reading and writing.
Example:
fileptr = open("file.txt","r")
if fileptr:
print("file is opened successfully")
THE CLOSE() METHOD
• Once all the operations are done on the
file, we must close it through our python
script using the close() method.
• Any unwritten information gets destroyed
once the close() method is called on a file
object.
• Syntax:
fileobject.close()
READING THE FILE
• To read a file using the python script, the
python provides us the read() method.
• The read() method reads a string from the
file.
• It can read the data in the text as well as
binary format.
• Syntax: fileobj.read(<count>)
• Here, the count is the number of bytes to be
read from the file starting from the
beginning of the file. If the count is not
specified, then it may read the content of
the file until the end.
Example:
fileptr = open("data.txt","r");
content = fileptr.read(9);
print(type(content))

print(content)

fileptr.close()
READ LINES OF THE FILE
• Python facilitates us to read the file line by
line by using a function readline().
• The readline() method reads the lines of
the file from the beginning
fileptr = open("data.txt","r");

content = fileptr.readline();
print(content)

content = fileptr.readline();
print(content)
fileptr.close()
LOOPING THROUGH THE FILE
• By looping through the lines of the file, we can
read the whole file.
• Example:
fileptr = open("data.txt","r");
for i in fileptr:
print(i)
# i contains each line of the file
WRITING THE FILE
• To write some text to a file, we need to
open the file using the open method
with one of the following access modes.
• a: It will append the existing file. The file
pointer is at the end of the file. It
creates a new file if no file exists.
• w: It will overwrite the file if any file
exists. The file pointer is at the
beginning of the file.
fileptr = open("file.txt","a");

fileptr.write(“this will be written.")

#closing the opened file


fileptr.close();
MODIFYING FILE POINTER POSITION
• sometimes we need to change the file pointer
location externally since we may need to read or
write the content at various locations.
• the python provides us the seek() method which
enables us to modify the file pointer position
externally.
• Syntax: <file-ptr>.seek(offset[, from])
offset: It refers to the new position of the file
pointer within the file.
• from: It indicates the reference position from
where the bytes are to be moved. If it is set to
0, the beginning of the file is used as the
reference position. If it is set to 1, the current
position of the file pointer is used as the
reference position. If it is set to 2, the end of
the file pointer is used as the reference
position.
• Python 3 only supports text file seeks from
the beginning of the file.
• In text files (those opened without b in the
mode string), only seeks relative to the
beginning of the file are allowed (the
exception being seeking to the very file end
with seek(0, 2)).
fileptr = open("data.txt","r")
print("The filepointer is at byte :",
fileptr.tell())
content = fileptr.read(9);
print("After reading Content, the
filepointer is at:",fileptr.tell())
fileptr.seek(10);
print("After seek, the filepointer is at:“
,fileptr.tell())
PYTHON OS MODULE
• The os module provides us the functions that
are involved in file processing operations like
renaming, deleting, etc.

Renaming the file


• The os module provides us the rename()
method which is used to rename the specified
file to a new name.
• Syntax:
rename(“current-name”, ”new-name”)
Example:
os.rename("file2.txt","file3.txt")
Removing the file
• The os module provides us the remove()
method which is used to remove the specified
file.
• Syntax:
os.remove(“file-name”)

Creating the new directory


• The mkdir() method is used to create the
directories in the current working directory.
• Syntax:
os.mkdir(“directory name”)
Changing the current working
directory:
• The chdir() method is used to change the
current working directory to a specified
directory.
• Syntax:
chdir("new-directory")

The getcwd() method:


• This method returns the current working
directory.
Syntax:
os.getcwd()
Deleting directory
• The rmdir() method is used to delete the
specified directory.
• Syntax:
os.rmdir(“directory name”)
import os;
os.rename("file2.txt","file3.txt")
os.remove("file3.txt")
os.mkdir("new")
os.chdir("new")
print(os.getcwd())

os.rmdir("new")
PYTHON
EXCEPTIONS
• An exception can be defined as an
abnormal condition in a program
resulting in the disruption in the flow of
the program.
• Whenever an exception occurs, the
program halts the execution, and thus the
further code is not executed.
COMMON EXCEPTIONS
Sr. Exception Name & Description
1 Exception
Base class for all exceptions
2 ZeroDivisionError
division by zero
3 SystemExit
Raised by the sys.exit() function.
4 StandardError
Base class for all built-in exceptions except StopIteration
and SystemExit.
5 ArithmeticError
Base class for all errors that occur for numeric calculation.
6 OverflowError
Raised when a calculation exceeds maximum limit for a
numeric type.
7 FloatingPointError
Raised when a floating point calculation fails.
8 AttributeError
Raised in case of failure of attribute reference or
assignment.
9 EOFError
Raised when there is no input from either the raw_input()
or input() function and the end of file is reached.
10 ImportError
Raised when an import statement fails.
11 KeyboardInterrupt
Raised when the user interrupts program execution,
usually by pressing Ctrl+c.
12 IndexError
Raised when an index is not found in a sequence.
13 KeyError
Raised when the specified key is not found in the
dictionary.
14 NameError
Raised when an identifier is not found in the local or
global namespace.
15 EnvironmentError
Base class for all exceptions that occur outside the
Python environment.
16 IOError
Raised when an input/ output operation fails, such as the
print statement or the open() function when trying to open
a file that does not exist.
17 SyntaxError
Raised when there is an error in Python syntax.
18 IndentationError
Raised when indentation is not specified properly.
19 SystemError
Raised when the interpreter finds an internal problem, but
when this error is encountered the Python interpreter
does not exit.
20 SystemError
Raised when the interpreter finds an internal problem,
but when this error is encountered the Python interpreter
does not exit.
21 SystemExit
Raised when Python interpreter is quit by using the
sys.exit() function. If not handled in the code, causes the
interpreter to exit.
22 TypeError
Raised when an operation or function is attempted that is
invalid for the specified data type.
23 ValueError
Raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid
values specified.
24 RuntimeError
Raised when a generated error does not fall into any
category.
PROBLEM WITHOUT
HANDLING EXCEPTIONS
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = ",c)
#other code:
print("Hi I am other part of the program")
EXCEPTION HANDLING IN
PYTHON
• If the python program contains suspicious
code that may throw the exception, we must
place that code in the try block.
• The try block must be followed with the
except statement which contains a block of
code that will be executed if there is some
exception in the try block.
Syntax:
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code

#other code
• We can also use the else statement with the
try-except statement in which, we can place
the code which will be executed in the
scenario if no exception occurs in the try
block.
Syntax:
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block
is executed
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b;
except:
print("can't divide by zero")
else:
print("a/b = %d"%c)
try:
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
THE EXCEPT CLAUSE WITH
MULTIPLE EXCEPTIONS
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception
list,
then execute this block.
......................
else:
If there is no exception then execute this block.
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
• Python facilitates us to not specify the
exception with the except statement.
• We can declare multiple exceptions in the
except statement since the try block may
contain the statements which throw the
different type of exceptions.
• We can also specify an else block along with
the try-except statement which will be
executed if no exception is raised in the try
block.
• The statements that don't throw the exception
should be placed inside the else block.
RAISING EXCEPTIONS
• An exception can be raised by using the
raise clause in python.
• Syntax:
raise Exception_class,<value>
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b==0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
USER DEFINED EXCEPTION
• The python allows us to create our
exceptions that can be raised from the
program and caught using the except
clause.
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)

try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)

You might also like