11 23CS2301 B 6 24Unit-4Module
11 23CS2301 B 6 24Unit-4Module
4.1 Exceptions:
When a Python program meets an error, it stops the execution of the rest of the program. An error
in Python might be either an error in the syntax of an expression or a Python exception.
An exception in Python is an incident that happens while executing a program that causes the
regular course of the program's commands to be disrupted. When a Python code comes across a
condition it can't handle, it raises an exception. An object in Python that describes an error is called
an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or
stop and quit.
If an exception is not caught in Python, it will propagate up through the call stack until it either
reaches a higher-level exception handler or, if no such handler exists, it will cause the program to
terminate. This termination typically results in the Python interpreter displaying a traceback, which
includes information about where the exception occurred and what type of exception it was.
In essence, if an exception is not caught, it will lead to an unhandled exception error, which can halt
the execution of the program abruptly. It's generally a good practice to catch exceptions where they
occur and handle them appropriately to prevent unexpected terminations and to gracefully manage
errors in the program.
Exceptions versus Syntax Errors- When the interpreter identifies a statement that has an error,
syntax errors occur.
For Example in below Code
string = "Python Exceptions"
for s in string:
if (s != o:
print( s )
1
IFETCE R 2023 ACADEMIC YEAR 2023-2024
Output:
if (s != o:
^
Syntax Error:
invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error. There was one
unclosed bracket in this case. Close it and rerun the program:
Code:
string = "Python Exceptions"
for s in string:
if (s != o):
print( s )
Output:
string = "Python Exceptions"
for s in string:
----> if (s != o):
print( s )
Name Error: name 'o' is not defined
We encountered an exception error after executing this code. When syntactically valid Python code
produces an error, this is the kind of error that arises.
The output's last line specified the name of the exception error code encountered. Instead of
displaying just "exception error", Python displays information about the sort of exception error that
occurred.
It was a Name Error in this situation. Python includes several built-in exceptions. However, Python
offers the facility to construct custom exceptions.
4.2 ERRORS AND EXCEPTIONS:
Errors and exceptions can lead to unexpected behavior or even stop a program from executing.
Python provides various functions and mechanisms to handle these issues and improve the
robustness of the code.
An error is an issue in a program that prevents the program from completing its task. In
comparison, an exception is a condition that interrupts the normal flow of the program. Both errors
and exceptions are a type of runtime error, which means they occur during the execution of a
program.
In simple words, the error is a critical issue that a normal application should not catch, while an
exception is a condition that a program should catch.
4.2.1 Errors:
Errors or mistakes in a program are often referred to as bugs. They are almost always the fault of
the programmer.
The error message has two parts:
2
IFETCE R 2023 ACADEMIC YEAR 2023-2024
It returns a syntax error message because after the if statement a colon: is missing. We can fix this by
writing the correct syntax.
2. Runtime errors
If a program is syntactically correct – that is, free of syntax errors – it will be run by the
Python interpreter. However, the program may exit unexpectedly during execution if it encounters
a runtime error, a problem which was not detected when the program was parsed, but is only
revealed when a particular line is executed.(i.e) Runtime errors are also known as exceptions and
can occur for various reasons such as division by zero, attempting to access an index that is out of
range, or calling a function that does not exist.
Examples of Python runtime errors:
Division by zero.
3
IFETCE R 2023 ACADEMIC YEAR 2023-2024
4
IFETCE R 2023 ACADEMIC YEAR 2023-2024
results. The for loop is iterating from 1to n-1instead of from 1 to n , causing the issue. This means
that the factorial is being calculated incorrectly, resulting in an incorrect output.
Solution
To fix this logical error, we need to change the range of the for loop to include the number n itself.
Here's the corrected code:
def calculate_factorial(n):
result = 1
for i in range(1, n+1):
result = result * i
return result
print(calculate_factorial(5))
Output:
120
4.3 HANDLING EXCEPTION
Exception handling in python allows you to separate error-handling code from normal code.
An exception is a Python object which represents an error.
As with code comments, exceptions help you to remind yourself of what the program expects.
It clarifies the code and enhances readability.
Allows you to stimulate consequences as the error-handling takes place in one place and in one
manner.
An exception is a convenient method for handling error messages.
In Python, you can raise an exception in the program by using the raise exception method.
Raising an exception helps you to break the current code execution and returns the exception
back to expection until it is handled.
Processing exceptions for components that can’t handle them directly.
Exceptions can come in the following two exception classes:
Checked exceptions. Also called compile-time exceptions, the compiler checks these exceptions
during the compilation process to confirm if the exception is being handled by the programmer.
If not, then a compilation error displays on the system. Checked exceptions include
SQLException and ClassNotFoundException.
Unchecked exceptions. Also called runtime exceptions, these exceptions occur during program
execution. These exceptions are not checked at compile time, so the programmer is responsible
for handling these exceptions. Unchecked exceptions do not give compilation errors. Examples
of unchecked exceptions include NullPointerException and IllegalArgumentException.
4.3.1 Rules of Exceptions
Here are some essential rules of Python exception handling:
Exceptions must be class objects
For class exceptions, you can use a try statement with an except clause which mentions a
particular class.
5
IFETCE R 2023 ACADEMIC YEAR 2023-2024
6
IFETCE R 2023 ACADEMIC YEAR 2023-2024
Example:
try
}
catch (ArrayIndexOutOfBoundsException e) {
}
iii. Finally Statement in Python
Whether or not there is an exception, the finally block always runs. You may write a
block of code that comes after a try-catch block by using the final keyword.
A clause is optional, to sum up. It aims to provide cleanup procedures that must be
followed in all circumstances.
try:
raise KeyboardInterrupt
finally:
print 'welcome, world!'
Output:
Welcome, world!
Keyboard Interrupt
Finally, the clause is executed before the try statement.
iv. Raise Statement in Python - The raise statement specifies an argument that initializes the exception
object. Here, a comma follows the exception name, and argument or tuple of the argument that
follows the comma.
Syntax:
raise [Exception [, args [, traceback]]]
In this syntax, the argument is optional, and at the time of execution, the exception
argument value is always none.
4.4 Built-In Exceptions:
The built-in exceptions can be generated by the interpreter or built-in functions.
There are several built-in exceptions in Python that are raised when errors occur. These
built-in exceptions can be viewed using the local() built-in functions as follows :
>>> locals()['__builtins__']
This returns a dictionary of built-in exceptions, functions and attributes.
In Python, all errors must be instances of BaseException class. The language provides a
set of built-in exceptions which you can use in built-in functions.
1. Base Classes:
The following exceptions are used mostly as base classes for other exceptions.
7
IFETCE R 2023 ACADEMIC YEAR 2023-2024
This is the base class for all built-in exceptions. It is not meant to be directly inherited by
user-defined classes. For, user-defined classes, Exception is used. This class is
responsible for creating a string representation of the exception using str() using the
arguments passed. An empty string is returned if there are no arguments.
args : The args are the tuple of arguments given to the exception constructor.
with_traceback(tb) : This method is usually used in exception handling. This method
sets tb as the new traceback for the exception and returns the exception object.
Code :
try:
...
except SomeException:
tb = sys.exc_info()[2]
raise OtherException(...).with_traceback(tb)
i. exceptionException - This is the base class for all built-in non-system-exiting
exceptions. All user-defined exceptions should also be derived
from this class.
ii. exceptionArithmeticError - This class is the base class for those built-in exceptions
that are raised for various arithmetic errors such as
OverflowError
ZeroDivisionError
FloatingPointError
Example :
try:
a = 10/0
print (a)
print ("This statement is raising an arithmetic exception.")
else:
print ("Success.")
Output :
This statement is raising an arithmetic exception.
iii. exceptionBufferError:
This exception is raised when buffer related operations cannot be performed.
iv. exceptionLookupError:
This is the base class for those exceptions that are raised when a key or index used on a
mapping or sequence is invalid or not found. The exceptions raised are :
KeyError
IndexError
Example :
try:
a = [1, 2, 3]
8
IFETCE R 2023 ACADEMIC YEAR 2023-2024
print (a[3])
print ("Index out of bound error.")
else:
print ("Success")
Output : Index out of bound error.
2. CONCRETE EXCEPTIONS:
The following exceptions are the exceptions that are usually raised.
The previously handled exception can serve as the implicit context for a new exception
that is raised inside of an exception handler.
This can help with exception chaining and provide you more details about the error. You
can designate the original exception as the new exception’s cause by using the syntax
raise raise new_exc from original_exc.
i. exceptionAssertionError: - An AssertionError is raised when an assert statement fails.
Example :
assert False, 'The assertion failed'
Output :
Traceback (most recent call last):
File "exceptions_AssertionError.py", line 12, in
assert False, 'The assertion failed'
AssertionError: The assertion failed
ii. exception AttributeError: - An AttributeError is raised when an attribute reference or
assignment fails such as when a non-existent attribute is referenced.
Example :
class Attributes(object):
pass
object = Attributes()
print (object.attribute)
Output :
Traceback (most recent call last):
File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in
print object.attribute
AttributeError: 'Attributes' object has no attribute 'attribute'
iii. exception EOFError: - An EOFError is raised when built-in functions like input() hits an end-
of-file condition (EOF) without reading any data. The file methods like readline() return an
empty string when they hit EOF.
Example :
while True:
data = input('Enter name : ')
print ('Hello ', data)
Output :
9
IFETCE R 2023 ACADEMIC YEAR 2023-2024
10
IFETCE R 2023 ACADEMIC YEAR 2023-2024
Example :
array = [ 0, 1, 2 ]
print (array[3])
Output :
Traceback (most recent call last):
File "exceptions_IndexError.py", line 13, in
print array[3]
IndexError: list index out of range
ix. exception KeyError: - A KeyError is raised when a mapping key is not found in the set of
existing keys.
Example :
array = { 'a':1, 'b':2 }
print (array['c'])
Output :
Traceback (most recent call last):
File "exceptions_KeyError.py", line 13, in
print array['c']
KeyError: 'c'
x. exception KeyboardInterrupt: - This error is raised when the user hits the interrupt key such as
Control-C or Delete.
Example :
try:
print ('Press Return or Ctrl-C:',)
Output :
Press Return or Ctrl-C: ^CCaught KeyboardInterrupt
11
IFETCE R 2023 ACADEMIC YEAR 2023-2024
xi. exception MemoryError: - This error is raised when an operation runs out of memory.
Example :
def fact(a):
factors = []
for i in range(1, a+1):
if a%i == 0:
factors.append(i)
return factors
num = 600851475143
print (fact(num))
Output :
Traceback (most recent call last):
File "4af5c316c749aff128df20714536b8f3.py", line 9, in
print fact(num)
File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact
for i in range(1, a+1):
xii. MemoryErrorexception NameError: - This error is raised when a local or global name is not
found. For example, an unqualified variable name.
Example :
def func():
print ans
func()
Output :
Traceback (most recent call last):
File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in
func()
File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func
print ans
NameError: global name 'ans' is not defined
xiii. exception NotImplementedError: - This exception is derived from RuntimeError. Abstract
methods in user defined classed should raise this exception when the derived classes override the
method.
Example :
class BaseClass(object):
"""Defines the interface"""
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
"""The interface, not implemented"""
raise NotImplementedError(self.__class__.__name__ + '.do_something')
12
IFETCE R 2023 ACADEMIC YEAR 2023-2024
class SubClass(BaseClass):
"""Implements the interface"""
def do_something(self):
"""really does something"""
print (self.__class__.__name__ + ' doing something!')
SubClass().do_something()
BaseClass().do_something()
Output :
Traceback (most recent call last):
File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in
BaseClass().do_something()
File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something
raise NotImplementedError(self.__class__.__name__ + '.do_something')
NotImplementedError: BaseClass.do_something
xiv. exception OSError([arg]): - The OSError exception is raised when a system function returns a
system-related error, including I/O failures such as “file not found” or “disk full” errors.
Example :
def func():
print (ans)
func()
Output :
Traceback (most recent call last):
File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in
print i, os.ttyname(i)
OSError: [Errno 25] Inappropriate ioctl for device
xv. exception OverflowError: - The OverflowError is raised when the result of an arithmetic
operation is out of range. Integers raise MemoryError instead of OverflowError. OverflowError
is sometimes raised for integers that are outside a required range. Floating point operations are
not checked because of the lack of standardization of floating point exception handling in C.
Example :
import sys
print ('Regular integer: (maxint=%s)' % sys.maxint)
try:
i = sys.maxint * 3
print ('No overflow for ', type(i), 'i =', i)
except OverflowError, err:
print ('Overflowed at ', i, err)
print()
print ('Long integer:')
for i in range(0, 100, 10):
13
IFETCE R 2023 ACADEMIC YEAR 2023-2024
print ('%2d' % i, 2L ** i)
print()
print ('Floating point values:')
try:
f = 2.0**i
for i in range(100):
print (i, f)
f = f ** 2
except OverflowError, err:
print ('Overflowed after ', f, err)
Output :
Regular integer: (maxint=9223372036854775807)
No overflow for i = 27670116110564327421
Long integer:
01
10 1024
20 1048576
30 1073741824
40 1099511627776
50 1125899906842624
60 1152921504606846976
70 1180591620717411303424
80 1208925819614629174706176
90 1237940039285380274899124224
Floating point values:
0 1.23794003929e+27
1 1.53249554087e+54
2 2.34854258277e+108
3 5.5156522631e+216
Overflowed after 5.5156522631e+216 (34, 'Numerical result out of range')
xvi. exception RecursionError: - The RecursionError is derived from the RuntimeError. This
exception is raised when the interpreter detects that the maximum recursion depth is exceeded.
xvii. exception ReferenceError: - The ReferenceError is raised when a weak reference proxy is used
to access an attribute of the referent after the garbage collection.
Example :
import gc
import weakref
class Foo(object):
def __init__(self, name):
self.name = name
14
IFETCE R 2023 ACADEMIC YEAR 2023-2024
def __del__(self):
print ('(Deleting %s)' % self)
obj = Foo('obj')
p = weakref.proxy(obj)
print ('BEFORE:', p.name)
obj = None
print ('AFTER:', p.name)
Output :
BEFORE: obj
(Deleting )
AFTER:
Traceback (most recent call last):
File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in
print 'AFTER:', p.name
ReferenceError: weakly-referenced object no longer exists
xviii. exception RuntimeError:- The RuntimeError is raised when no other exception applies. It
returns a string indicating what precisely went wrong.
xix. exception StopIteration:- The StopIteration error is raised by built-in function next() and an
iterator‘s __next__() method to signal that all items are produced by the iterator.
Example :
Arr = [3, 1, 2]
i=iter(Arr)
print (i)
print (i.next())
print (i.next())
print (i.next())
print (i.next())
Output : 3
1
2
Traceback (most recent call last):
File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in
print i.next()
StopIteration
xx. exception SyntaxError: -
The SyntaxError is raised when the parser encounters a syntax error. A syntax error may occur in
an import statement or while calling the built-in functions exec() or eval(), or when reading the
initial script or standard input.
Example :
try:
15
IFETCE R 2023 ACADEMIC YEAR 2023-2024
16
IFETCE R 2023 ACADEMIC YEAR 2023-2024
Output :
Global name error: global name 'unknown_global_name' is not defined
Local name error: local variable 'local_val' referenced before assignment
xxv. exception UnicodeError: -This exception is a subclass of ValueError. UnicodeError is raised
when a Unicode-related encoding or decoding error occurs.
xxvi. exception ValueError: - A ValueError is raised when a built-in operation or function receives
an argument that has the right type but an invalid value.
Example :
print (int('a'))
Output :
Traceback (most recent call last):
File "44f00efda935715a3c5468d899080381.py", line 1, in
print int('a')
ValueError: invalid literal for int() with base 10: 'a'
xxvii. exception ZeroDivisionError: - A ZeroDivisionError is raised when the second argument of a
division or modulo operation is zero. This exception returns a string indicating the type of the
operands and the operation.
Example :
print (1/0)
Output : Traceback (most recent call last):
File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in
print 1/0
xxviii. ZeroDivisionError: - integer division or modulo by zero.
Example:
a = 10
b=0
print(a/b)
Output:
File "test.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zero
The code in the earlier example can be updated to use an if statement to check if the
denominator is 0:
a = 10
b=0
if b == 0:
print("Cannot divide by zero")
else:
print(a/b)
Output: Cannot divide by zero . A try-except block can also be used to catch and handle this error
17
IFETCE R 2023 ACADEMIC YEAR 2023-2024
EOFError When the input() method encounters a “end of file” circumstance, it throws an
error (EOF)
GeneratorExit When the close() method of a generator is called, this variable is raised.
ImportError When the imported module cannot be found, this exception is thrown.
IndexError When the index of a sequence is out of range, this value is raised.
18
IFETCE R 2023 ACADEMIC YEAR 2023-2024
KeyboardInterrupt When the user pushes Ctrl+C, Ctrl+Z, or Delete, this exception is thrown.
When a variable is not discovered in the local or global scope, this exception
NameError
is raised.
OSError When a system operation results in a system-related error, this flag is raised.
OverflowError When the result of a numerical calculation is too huge, an error is raised.
This Is an Exception When a weak reference object does not exist, an error is
ReferenceError
raised.
RuntimeError When an error does not fit into any of the other categories, it is raised.
StopIteration Raised by the next() function for the iterator that has no more items to return.
SyntaxError When a syntax problem occurs, the parser raises this exception.
19
IFETCE R 2023 ACADEMIC YEAR 2023-2024
UnicodeEncodeError When a Unicode-related problem occurs during encoding, this flag is raised.
UnicodeDecodeError When a Unicode-related error occurs while decoding, this flag is raised.
It defines an error. When there is an issue with a Unicode translation, this flag
UnicodeTranslateError
is raised.
Table 4.1 The Built-In Exception Types And The Most Typical Conditions In Which They Occur.
20
IFETCE R 2023 ACADEMIC YEAR 2023-2024
21
IFETCE R 2023 ACADEMIC YEAR 2023-2024
self.value = value
# This will help to display the message of the exception
22
IFETCE R 2023 ACADEMIC YEAR 2023-2024
def message(self):
return(repr(self.value))
try:
raise(MyUserDefinedError(9*8))
# returnedErrorMessage will store the value of the message or anything which will
be returned by the exception
except MyUserDefinedError as returnedErrorMessage:
print ('The occurrence of the new exception is identified : ', returnedErrorMessage.value)
The execution of the above program gives the following output showing the calculated value of 9 * 8
returned from the exception class, which we defined.
Output:
Example #2 - Let us consider one more example of a user-defined exception. In this example, we will try
to derive the error from the super class of Exception. This type of superclass exception is mostly used when
we have a single module that should handle many different types of errors. We will try to do this by using
this module to define the base class for our exceptions. Then, different subclasses will be created to define
each exception class for distinct possible errors that need to be handled.
Code:
# Class which is derived from the main base class of Exception is DerivedClassError class
class DerivedClassError(Exception):
# Even though DerivedClassError is derived from the main base class of exceptions,
# it will be used and considered as the base class for our user defined exception class
pass
class TransDerivedClassError(DerivedClassError):
# This transition will occur when the transition will try to
# perform the state which is actually not permitted to it
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
# message will store the value generated from the error
self.message = message
try:
raise(TransDerivedClassError(4,6*4,"Not Permitted"))
# DerivedClassError will store the value of the user defined exception
except TransDerivedClassError as DerivedClassError:
print('There is an occurrence of exception: ',DerivedClassError.message)
23
IFETCE R 2023 ACADEMIC YEAR 2023-2024
The execution of the above program gives the following output showing the message “Not Permitted”
returned from the exception class, which we defined.
Output:
Example #3 - We can even consider the standard predefined exceptions as the base class while creating our
new user defined exception. Let us consider one of the examples of that type. RuntimeError is raised when
the error which is occurred cannot be considered in any of the available categories of exceptions.
RuntimeError is the in-built exception in python. Therefore, we can consider this class as the base class for
our user-defined class instead of the main Exception class. The following program illustrates the usage of
the same.
Code:
# SampleError is derived from the RuntimeError instead of main base class of Exception
class SampleError(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
raise SampleError("Exception")
except SampleError as message:
print (message.args)
The execution of the above program gives the following output and works in a similar way as it would
have in case if we must have extended the main Exception class instead of RuntimeError class as the
consideration of base class.
Output:
4.5 FILES:
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).For example, main.py is a file that is always used to
store Python code.
File handling in Python is a powerful and versatile tool that can be used to perform a wide
range of operations. 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.
In Python, there is no need for importing external library to read and write files. Python
provides an inbuilt function for creating, writing and reading 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.
24
IFETCE R 2023 ACADEMIC YEAR 2023-2024
25
IFETCE R 2023 ACADEMIC YEAR 2023-2024
That’s because all the binary files will be encoded in the binary format, which can be
understood only by a computer or machine. For handling such binary files we need a specific
type of software to open it.
For Example, You need Microsoft word software to open .doc binary files. Likewise, you
need a pdf reader software to open .pdf binary files and you need a photo editor software to
read the image files and so on.
2. Text files in Python- Text files don’t have any specific encoding and it can be opened in
normal text editor itself. Text files are those which store data in the form of characters or
strings.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
4.7 File Operations:
In Python, file operations are essential for reading and writing data to files, and they play a
crucial role in data manipulation, analysis, and storage.
When working with large datasets in machine learning problems, working with files is a basic
necessity. Since Python is a majorly used language for data science, For performing file
operations, a file needs to be opened first.
Then follows the necessary operations to be performed by the user on our file. After all the
desired operations are performed, the file needs to be closed. Closing a file is necessary as
it would save the changes made on our file from the current session.
26
IFETCE R 2023 ACADEMIC YEAR 2023-2024
Opens a file and returns a file object. The filename argument is a string that specifies
open(filename,
the name of the file to open, and the mode argument specifies the mode in which to
mode)
open the file (e.g. ‘r’ for read mode, ‘w’ for write mode, etc.).
Closes the file object. Any further operations on the file object will raise a
close()
ValueError. It’s a good practice to always close files after they have been opened.
Reads and returns a string from the file. If size is specified, at most size characters
read(size=-1)
will be read. If size is not specified or is negative, the entire file will be read.
Reads and returns a single line from the file. If size is specified, at
readline(size=-1) most size characters will be read from the line. If size is not specified or is negative,
the entire line will be read.
Reads and returns a list of lines from the file. If hint is specified, at most hint bytes
readlines(hint=-1)
will be read. If hint is not specified or is negative, all the lines will be read.
write(string) Writes the string to the file. Returns the number of characters written.
Writes a sequence of strings to the file. The sequence can be any iterable object (e.g. a
writelines(sequence)
list, a tuple, etc.).
Changes the file position to the given offset. The whence argument is optional and
seek(offset[, defaults to 0, which means the offset is relative to the beginning of the file. Other
whence]) values for whence are 1 (relative to the current position) and 2 (relative to the end of
the file).
Truncates the file to at most size bytes. If size is not specified, the entire file will be
truncate(size=None)
truncated.
Flushes the write buffer of the file. This is useful when writing to a file that is being
flush()
accessed by multiple processes or threads.
27
IFETCE R 2023 ACADEMIC YEAR 2023-2024
The file path including the file name and the extension we want to open, is to be passed
as a string
The mode in which we want to open the file, to be passed as a string.Thus, the syntax for
opening a file would look like this:
1. open(“”, “”)- Indeed there are other arguments as well in the open() function which are
optional and are used as per the requirement of the user. Let’s look at an example for
opening a file. Suppose if we have a file named myfile.txt on our desktop, it can be opened
by:
open(“C:UsersRahulDesktopmyfile.txt”)
Unquestionably, if our current working directory of the Python file is the same as
our file (here desktop), there is no need to specify the full path. In such a case, our
open() function would look like:
2. open(“myfile.txt”) - For the ease of code implementation, let us consider our current
working directory the same as the location our text files .Python has a wide range of file
opening modes available by default. These modes specify in which mode our file needed to
be opened. Each file opening mode comes with its default functionality and one can select
the appropriate model based on the need. As discussed above, the file opening mode
argument is an important factor that decides whether we want to read, write or update the
contents of an existing file.
File Opening Modes in Python:
Mode Description Example
Read mode. Opens the file for reading (default mode). If the file doesn’t
r file = open('example.txt', 'r')
exist, an error will be raised.
Write mode. Opens the file for writing. If the file exists, it will be
w file = open('example.txt', 'w')
truncated. If the file doesn’t exist, it will be created.
Append mode. Opens the file for writing, but appends new data to the
a end of the file instead of overwriting existing data. If the file doesn’t file = open('example.txt', 'a')
exist, it will be created.
Exclusive creation mode. Opens the file for writing, but only if it doesn’t
x file = open('example.txt', 'x')
already exist. If the file exists, an error will be raised.
b Binary mode. Opens the file in binary mode instead of text mode. file = open('example.txt', 'rb')
t Text mode (default). Opens the file in text mode instead of binary mode. file = open('example.txt', 'rt')
+ Update mode. Opens the file for both reading and writing. file = open('example.txt', 'r+')
28
IFETCE R 2023 ACADEMIC YEAR 2023-2024
The modes discussed above are being used on a text file. To use these modes for a binary
file, we need to use a different combination of file opening mode arguments.
Using ‘b’ with any mode, For example, ‘ab’, ‘rb’, ‘wb’, ‘rb+’, the file opens in binary
mode. It is used for non-textual files like image, sound, executable (.exe) files.
Example: To open our file myfile.txt in b mode:
open("myfile.txt", "rb")
Opening a file is not enough. This open function needs to be stored into a variable as this will
be used later for writing & reading the file. Here we will assign a variable to our file:
file = open("myfile.txt", "r")
2. Reading a File Operation in Python- Now that we have opened a file, we can start performing
operations to it. In this section, we will look at the reading functionality of files using Python.
Before start reading the file, as discussed, we must open the file in ‘r’ mode, since we are
going to read the contents of the file. Let us assume that our file myfile.txt already has
some textual data present in it.
file = open("myfile.txt", "r")
print(file.read())
On executing this code, we get:
The .read() method to our variable file gives the content of the file as output. We can also
specify the number of characters we want to read at once.
file = open("myfile.txt", "r")
print(file.read(8))
On executing this code, we get:
This will print the 8 characters from the point until the file has been read earlier.Since we
executed the open statement before the .read() method, the file is opened again and the
cursor is moved at the start point, i.e. index 0. Thus 8 characters are being read from the
start point.
Let’s understand this with another example. Given our file named myfile.txt having some
content “Hello, how you all have been doing?”. After opening a file, if we
use print(file.read(6)), it will first give “Hello,” as output & if use print(file.read(8)), it
will start reading 8 characters file from the point where the first read function left off i.e. ”
how you”
file = open("myfile.txt", 'r')
print(file.read(6))
print(file.read(8))
On executing this code, we get:
29
IFETCE R 2023 ACADEMIC YEAR 2023-2024
As a result, when all the characters of the file are being read & if we try to use
the .read() method again, it will give an empty string as output.
The .readline() method prints each line from our file, every time we execute this function,
until the end of the file is reached. Let’s add some additional lines to our text file to
illustrate this example.
file = open("myfile.txt", 'r')
print(file.readline())
print(file.readline())
On executing this, we get:
This will print the first two lines of our file, separated by a newline character.
The .readlines() method always gives a list of all the lines of our file as list elements.
file = open("myfile.txt", 'r')
print(file.readlines())
On executing this we get:
A major difference between the .read() method and the .readline() method
is, .read() method focuses on reading each character from a file while
the .readline() focuses on reading individual lines from a file.
3. Writing/Creating a File - Another useful operation widely used, after opening a file, is writing
into a file. Writing into a file in Python is easy but an attentive task. Writing into a file is typically
done by opening the file in write ‘w’ or append ‘a’ mode. Writing into a file can be done using
the .write() method to our file.
Caution needed to be followed while using the ‘w’ write mode as it can erase existing
content present in the file.
Let’s understand this with an example. If we want to add content to our existing file,
myfile.txt, first we need to open it in the ‘w’ write mode and use the .write() method on
our file.
The content to be written into the file needs to be passed as a string. It’s a good practice to
add a newline character ‘n’ to add a line between sentences. This improves the readability
for the user and is also useful while using the .readline() and .readlines() methods to
distinguish between the lines.
file = open("myfile.txt", "w")
file.write("Hello Alln")
On executing this code, we get:
30
IFETCE R 2023 ACADEMIC YEAR 2023-2024
Here, on execution, the .write() method returns the number of characters written into the
file.
While writing into a file, if the file opened in ‘w’ or ‘w+‘ mode does not exist, a new file
will be created in the same name in our present working directory.
Example:
file = open("file.txt", "w")
On executing this code, we get:
Here, previously the file file.txt does not exist in the current working directory and later it
got created. If file.txt would have already existed, it will erase all the content and the file
will become empty.
Another file mode used for writing to the file is the ‘a’ append mode. This creates a new
file if the specified file does not exist in the current working directory.
Unlike ‘w’ mode, it does not remove the existing content from the file. Instead, it appends
or adds the new content at the end of the file. Writing in append mode can be done using
the .write() method.
Example: file = open("myfile.txt", "a"
file.write("I am using append moden")
On executing this code, we get:
This will append the new content at the end of existing into our specified file.
4. Closing a File in Python- At last, after opening and performing the reading, writing operations, it
is important to close the file. This is done using .close() method. Let’s understand this with an
Example:
file = open("myfile.txt", 'r')
print(file.read())
file.close()
It is always a good practice to close a file after performing desired operations to it. Thus makes
sure that all our changes have been saved to the file. In the later sections, where we will try to
rename and remove the files. To accomplish these tasks, we mu st close the files to permit
renaming and removing the files.
31
IFETCE R 2023 ACADEMIC YEAR 2023-2024
5. Cursor Positioning Methods - Python has a couple of essential methods for the positioning of the
cursor in our file. The methods are as follows:
i. The .seek() method - The .seek() method in Python is used to change the cursor to a specific
position.
file = open("myfile.txt", 'r')
file.seek(0)
file.close()
This will move our cursor to index position 0 & file reading will start from the start point
again.
ii. The .tell() method - The .tell() method in Python prints the current position of our cursor.
file = open("myfile.txt", 'r')
file.tell()
This will give the position up to which file has been read.
Since we have used the .seek(0) method previously to move the cursor at index position 0,
we got 0 as output for using the .tell() method.
iii. Truncating a File - Truncating a File is also possible in Python. By using
the .truncate() method, we can truncate the file up to the desired length. Let’s understand this
with an example:
file = open('myfile.txt', 'w')
file.truncate(20)
file.close()
32
IFETCE R 2023 ACADEMIC YEAR 2023-2024
os.rename('myfile.txt', 'ourfile.txt')
Since we deleted this file, we cannot open this again and as a result, getting errors.
33