0% found this document useful (0 votes)
23 views23 pages

Chapter 6

Uploaded by

vidyadevi6996
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views23 pages

Chapter 6

Uploaded by

vidyadevi6996
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

FILE I/O HANDLING AND

EXCEPTION HANDLING
I/O OPERATIONS
• Reading Keyboard Input:
 Python provides two built-in functions to read a line of text from standard
input, which by default comes from the keyboard. These functions are −
1. input(prompt)
2. input()
 The input(prompt) Function :

The input([prompt]) function allows user input. It takes one argument. The
syntax is as follows:
Syntax: input(prompt)
Example:
x = input("Enter your name: ")
print(‘Hello ’ + x)
 The input() Function:

The input() function always evaluate the input provided by user and
return same type data. The syntax is as follows:
Syntax: x=input()
Example:
x=int(input())
print(type(x))
• Printing to 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
as follows –
The syntax is
Print(object(s),separator=separator,end=end,file=file,flush=flush)
 Parameter values:

1. Object(s) : It can be any object but will be converted to string before


primted.
2. sep=’seperator’ : Optional. Specify how to separate the objects, if there
are more than one. Default is ‘’.
3. end=’end’: Optional. Specify what to print at the end. Default is ‘\n’(line
feed).
4. file: Optional. An object with a write method, Default is sys.stdout
5. flush: Optional. A Boolean, specifying if the output is flushed(True) or
buffered(False). Default is False.
Example:
print("Python is really a great language,", "isn't it?")
FILE HANDLING
• What is a file?
 File is a named location on disk to store related information. It is
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
computer is turned off, we use files for future use of the data.
 Python supports file handling and allows users to handle files i.e., to read and
write files, along with many other file handling options, to operate on files.
 Python treats files differently as text or binary and this is important. Each line
of code includes a sequence of characters and they form a text file. Each line
of a file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character. It ends the current line and
tells the interpreter a new one has begun.
OPENING FILE IN DIFFERENT MODES
• Before performing any operation on the file like reading or writing, first, we have to
open that file. 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:
• r: open an existing file for a read operation.
• w: open an existing file for a write operation. If the file already contains some data then
it will be overridden.
• a: open an existing file for append operation. It won’t override existing data.
• r+: To read and write data into the file. The previous data in the file will be overridden.
• w+: To write and read data. It will override existing data.
• a+: To append and read data from the file. It won’t override existing data.
file = open(‘XYZ.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)

file = open(‘XYZ.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
USE OF STANDARD LIBRARY FUNCTION
• raw_input(): The raw_input([prompt]) function reads one line from
standard input and returns it as a string (removing the trailing newline).
str = raw_input("Enter your input: ")
print("Received input is : ", str)
• input(): The input([prompt]) function is equivalent to raw_input, except
that it assumes the input is a valid Python expression and returns the
evaluated result to you.
str = input("Enter your input: ")
print("Received input is : ", str)
• open(): 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.
file object = open(file_name [, access_mode][, buffering])
• close(): The close() method of a file object flushes any unwritten
information and closes the file object, after which no more writing can be
done. Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.
file = open(“XYZ.txt", ‘w’)
print("Name of the file: ", XYZ.name)
# Close opend file
XYZ.close()
• write(): The write() method writes any string to an open file. It is important to
note that Python strings can have binary data and not just text. The write()
method does not add a newline character ('\n') to the end of the string.
abc = open(“pqr.txt", "wb")
abc.write( "Python is a great language.\nYeah its great!!\n")
# Close opend file
abc.close()
• read(): The read() method reads a string from an open file. It is important to
note that Python strings can have binary data. apart from text data.
abc= open(“pqr.txt", "r+")
str = abc.read(10);
print("Read String is : ", str)
# Close opend file
abc.close()
• tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
• seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the
reference position from where the bytes are to be moved.
• rename() method takes two arguments, the current filename and the new filename.
• remove() method to delete files by supplying the name of the file to be deleted as
the argument.
• mkdir() method of the os module to create directories in the current directory.
• chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current
directory.
• getcwd() method displays the current working directory.
• rmdir() method deletes the directory, which is passed as an argument in the
method. Before removing a directory, all the contents in it should be removed.
RENAMING AND DELETING FILES
• Python os module provides methods that help you perform file-processing
operations, such as renaming and deleting files. To use this module you need to
import it first and then you can call any related functions.
 rename(): rename() method takes two arguments, the current filename and
the new filename.
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
 remove(): remove() method to delete files by supplying the name of the file
to be deleted as the argument.
import os
# Delete file test2.txt
os.remove("text2.txt")
DIRECTORIES IN PYTHON
• All files are contained within various directories, and Python has no problem handling these
too. The os module has several methods that help you create, remove, and change
directories.
 mkdir(): The mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method which contains the name of the
directory to be created.
import os
# Create a directory "test"
os.mkdir("test")
 chdir():The chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory.
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
 getcwd(): The getcwd() method displays the current working directory.
import os
# This would give location of the current directory
os.getcwd()
 rmdir(): The rmdir() method deletes the directory, which is passed as an
argument in the method. Before removing a directory, all the contents in it
should be removed.
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
FILE AND DIRECTORY RELATED STANDARD
FUNCTIONS

• https://www.tutorialspoint.com/python/file_methods.htm

• https://www.tutorialspoint.com/python/os_file_methods.htm
EXCEPTION HANDLING
• Error in Python can be of two types i.e. Syntax errors and Exceptions.
• Syntax Errors are the problems in a program due to which the program will
stop the execution.
• This error is caused by the wrong syntax in the code.
• It leads to the termination of the program.
amount = 10000
if(amount > 2999)
print("You are eligible to purchase order")
• Exceptions are raised when some internal events occur which changes the
normal flow of the program.
• 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.
marks = 10000
# perform division with 0
a = marks / 0
print(a)
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.
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")
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.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)

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)

except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
TRY WITH ELSE CLAUSE

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

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)
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.
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')
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
USER DEFINED EXCEPTION
• User may name their own exceptions by creating a new exception class.
• Exceptions need to be derived from the Exception class, either directly or indirectly. Although not
mandatory, most of the exceptions are named as names that end in “Error” similar to the naming
of the standard exceptions in python.
class MyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
try:
raise(MyError(3*2))
# Value of Exception is stored in error
except MyError as error:
print('A New Exception occured: ',error.value)

You might also like