Unit 2
Unit 2
File handling in Python involves interacting with files on your computer to read data from them or
write data to them. Python provides several built-in functions and methods for creating, opening,
reading, writing, and closing files.
Opening a File in Python
To perform any file operation, the first step is to open the file. Python's built-in open() function is
used to open files in various modes, such as reading, writing, and appending. The syntax for opening a
file in Python is −
file = open("filename", "mode")
Where, filename is the name of the file to open and mode is the mode in which the file is opened
(e.g., 'r' for reading, 'w' for writing, 'a' for appending).
File Opening Modes
Following are the file opening modes −
Sr.No. Modes & Description
r - Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
1
the default mode.
rb - Opens a file for reading only in binary format. The file pointer is placed at the beginning
2
of the file. This is the default mode.
r+ - Opens a file for both reading and writing. The file pointer placed at the beginning of the
3
file.
rb+ - Opens a file for both reading and writing in binary format. The file pointer placed at the
4
beginning of the file.
w - Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
5
creates a new file for writing.
6 b - Opens the file in binary mode
7 t - Opens the file in text mode (default)
8 + - open file for updating (reading and writing)
wb - Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
9
file does not exist, creates a new file for writing.
w+ - Opens a file for both writing and reading. Overwrites the existing file if the file exists. If
10
the file does not exist, creates a new file for reading and writing.
wb+ - Opens a file for both writing and reading in binary format. Overwrites the existing file if
11
the file exists. If the file does not exist, creates a new file for reading and writing.
a - Opens a file for appending. The file pointer is at the end of the file if the file exists. That is,
12
the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab - Opens a file for appending in binary format. The file pointer is at the end of the file if the
13 file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.
a+ - Opens a file for both appending and reading. The file pointer is at the end of the file if the
14 file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
ab+ -Opens a file for both appending and reading in binary format. The file pointer is at the
15 end of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
16 x- open for exclusive creation, failing if the file already exists
Once a file is opened and you have one file object, you can get various information related to that file.
Example 1
In the following example, we are opening a file in different modes −
# Opening a file in read mode
file = open("example.txt", "r")
Example 2
A file named "foo.txt" in binary write mode ("wb"), printing its name, whether it's closed, and its
opening mode, and then closing the file
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not: ", fo.closed)
print ("Opening mode: ", fo.mode)
fo.close()
Class
Creating a Class
To create a class in Python, use the class keyword followed by the class name and a colon.
Inside the class, you can define attributes and methods. For example:
class MyClass:
x=5
Creating an Object
An object is created by calling the class name followed by parentheses. For example:
p1 = MyClass()
print(p1.x)
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Here, the __init__ method initializes the name and age attributes of the Person class2.
The __str__ method controls what should be returned when the class object is represented as
a string. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
p1 = Person("John", 36)
print(p1)
Object Methods
Objects can also contain methods, which are functions that belong to the object. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Deleting Objects
Understanding Python classes and objects is fundamental for mastering Python programming.
They provide a way to structure and organize code into reusable components, facilitating
code reusability, modularity, and maintainability.
Python Exception Handling handles errors that occur during the execution of a program.
Exception handling allows to respond to the error, instead of crashing the running program. It
enables you to catch and manage errors, making your code more robust and user-friendly.
n= 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
except Block: except block enables us to handle the error or exception. If the code inside the
try block throws an error, Python jumps to the except block and executes it. We can handle
specific exceptions or use a general except to catch all exceptions.
else Block: else block is optional and if included, must follow all except blocks. The else block
runs only if no exceptions are raised in the try block. This is useful for code that should
execute if the try block succeeds.
finally Block: finally block always runs, regardless of whether an exception occurred or not.
It is typically used for cleanup operations (closing files, releasing resources).
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
except ValueError:
else:
finally:
print("Execution complete.")
You can't divide by zero!
Execution complete.
ZeroDivisionError
Raised when a division or modulo operation is performed with zero
as the divisor.
OverflowError
Raised when a numerical operation exceeds the maximum limit of a
data type.
FloatingPointError Raised when a floating-point operation fails.
AssertionError Raised when an assert statement fails.
AttributeError Raised when an attribute reference or assignment fails.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a dictionary key is not found.
MemoryError Raised when an operation runs out of memory.
NameError Raised when a local or global name is not found.
OSError Raised when a system-related operation (like file I/O) fails.
TypeError
Raised when an operation or function is applied to an object of
inappropriate type.
ValueError
Raised when a function receives an argument of the right type but
inappropriate value.
ImportError Raised when an import statement has issues.
ModuleNotFoundError Raised when a module cannot be found.
Catching specific exceptions makes code to respond to different exception types differently.
Example:
try:
inv = 1 / x
except ValueError:
print("Not Valid!")
except ZeroDivisionError:
print("Zero has no inverse!")
We can catch multiple exceptions in a single block if we need to handle them in the same
way or we can separate them if different types of exceptions require different handling.
Example:
try:
print("Error", e)
except IndexError:
print("Index out of range.")
def set(age):
if age < 0:
Raise an Exception
We raise an exception in Python using the raise keyword followed by an instance of the
exception class that we want to trigger. We can choose from built-in exceptions or define our
own custom exceptions by inheriting from Python’s built-in Exception class.
Basic Syntax:
if age < 0:
try:
set(-5)
except ValueError as e:
print(e)