0% found this document useful (0 votes)
0 views

Unit 2

The document provides a comprehensive overview of file handling in Python, covering how to open, read, write, and close files using various methods and modes. It also introduces the concepts of classes and objects in Python, explaining how to create them, initialize attributes, and define methods. Additionally, it discusses exception handling in Python, detailing the use of try, except, else, and finally blocks to manage errors effectively.

Uploaded by

dummy10802
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Unit 2

The document provides a comprehensive overview of file handling in Python, covering how to open, read, write, and close files using various methods and modes. It also introduces the concepts of classes and objects in Python, explaining how to create them, initialize attributes, and define methods. Additionally, it discusses exception handling in Python, detailing the use of try, except, else, and finally blocks to manage errors effectively.

Uploaded by

dummy10802
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

File Handling in Python

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")

# Opening a file in write mode


file = open("example.txt", "w")

# Opening a file in append mode


file = open("example.txt", "a")

# Opening a file in binary read mode


file = open("example.txt", "rb")

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()

It will produce the following output −


Name of the file: foo.txt
Closed or not: False
Opening mode: wb

Reading a File in Python


Reading a file in Python involves opening the file in a mode that allows for reading, and then using
various methods to extract the data from the file. Python provides several methods to read data from a
file −
 read() − Reads the entire file.
 readline() − Reads one line at a time.
 readlines − Reads all lines into a list.
Example: Using read() method
In the following example, the read() method is used to read the whole file into a single string −
with open("example.txt", "r") as file:
content = file.read()
print(content)
Following is the output obtained −
Hello!!!

Example: Using readline() method


In here, we are using the readline() method to read one line at a time, making it memory efficient for
reading large files line by line −
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()
Output of the above code is as shown below −
Hello!!!

Example: Using readlines() method


Now, we are using the readlines() method to read the entire file and splits it into a list where each
element is a line −
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line, end='')
We get the output as follows −
Hello!!!

Writing to a File in Python


Writing to a file in Python involves opening the file in a mode that allows writing, and then using
various methods to add content to the file.
To write data to a file, use the write() or writelines() methods. When opening a file in write mode
('w'), the file's existing content is erased.
Example: Using the write() method
In this example, we are using the write() method to write the string passed to it to the file. If the file is
opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will
append the string to the end of the file −
Open Compiler
with open("foo.txt", "w") as file:
file.write("Hello, World!")
print ("Content added Successfully!!")
Output of the above code is as follows −
Content added Successfully!!
Example: Using the writelines() method
In here, we are using the writelines() method to take a list of strings and writes each string to the file.
It is useful for writing multiple lines at once −
Open Compiler
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
print ("Content added Successfully!!")
The result obtained is as follows −
Content added Successfully!!
Closing a File in Python
We can close a file in Python using the close() method. Closing a file is an essential step in file
handling to ensure that all resources used by the file are properly released. It is important to close files
after operations are completed to prevent data loss and free up system resources.
Example
In this example, we open the file for writing, write data to the file, and then close the file using the
close() method −
Open Compiler
file = open("example.txt", "w")
file.write("This is an example.")
file.close()
print ("File closed successfully!!")
The output produced is as shown below −
File closed successfully!!
Using "with" Statement for Automatic File Closing
The with statement is a best practice in Python for file operations because it ensures that the file is
automatically closed when the block of code is exited, even if an exception occurs.
Example
In this example, the file is automatically closed at the end of the with block, so there is no need to call
close() method explicitly −
Open Compiler
with open("example.txt", "w") as file:
file.write("This is an example using the with statement.")
print ("File closed successfully!!")
Following is the output of the above code −
File closed successfully!!
Handling Exceptions When Closing a File
When performing file operations, it is important to handle potential exceptions to ensure your
program can manage errors gracefully.
In Python, we use a try-finally block to handle exceptions when closing a file. The "finally" block
ensures that the file is closed regardless of whether an error occurs in the try block −
Open Compiler
try:
file = open("example.txt", "w")
file.write("This is an example with exception handling.")
finally:
file.close()
print ("File closed successfully!!")
After executing the above code, we get the following output −
File closed successfully!!

Class

Python Classes and Objects


123

In Python, classes and objects are fundamental concepts of object-oriented programming


(OOP). A class is a blueprint for creating objects, providing initial values for state (member
variables or attributes), and implementations of behavior (member functions or methods). An
object is an instance of a 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

Here, MyClass is a class with an attribute x set to 51.

Creating an Object

An object is created by calling the class name followed by parentheses. For example:
p1 = MyClass()
print(p1.x)

This creates an object p1 of MyClass and prints the value of x1.

The __init__ Method


The __init__ method is a special method that is called when an object is instantiated. It is
used to initialize the object's attributes. For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

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

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)

This will print "John (36)".

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()

This will print "Hello my name is John".

The self Parameter


The self parameter is a reference to the current instance of the class and is used to access
variables that belong to the class. It does not have to be named self, but it must be the first
parameter of any function in the class.

Modifying Object Properties

You can modify properties on objects like this:


p1.age = 40

This sets the age of p1 to 40.

Deleting Object Properties

You can delete properties on objects using the del keyword:


del p1.age

This deletes the age property from the p1 object1.

Deleting Objects

You can delete objects using the del keyword:


del p1

This deletes the p1 object.

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

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.

Example: Trying to divide a number by zero will cause an exception.

n= 10
try:
res = n / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:
print("Can't be divided by zero!")

Syntax and Usage


Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs

try, except, else and finally Blocks


 try Block: try block lets us test a block of code for errors. Python will “try” to execute the
code in this block. If an exception occurs, execution will immediately jump to the except
block.

 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:

print("You can't divide by zero!")

except ValueError:

print("Enter a valid number!")

else:

print("Result is", res)

finally:
print("Execution complete.")
You can't divide by zero!
Execution complete.

Common Exceptions in Python


Python has many built-in exceptions, each representing a specific error condition. Some
common ones include:

Exception Name Description


BaseExceptionThe base class for all built-in exceptions.
Exception The base class for all non-exit exceptions.
ArithmeticError Base class for all errors related to arithmetic operations.

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.

Python Catching Exceptions


When working with exceptions in Python, we can handle errors more efficiently by
specifying the types of exceptions we expect. This can make code both safer and easier to
debug.

Catching Specific Exceptions

Catching specific exceptions makes code to respond to different exception types differently.

Example:

try:

x = int("str") # This will cause ValueError


#inverse

inv = 1 / x

except ValueError:

print("Not Valid!")

except ZeroDivisionError:
print("Zero has no inverse!")

Catching Multiple Exceptions

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:

a = ["10", "twenty", 30] # Mixed list of integers and strings

try:

total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to int

except (ValueError, TypeError) as e:

print("Error", e)

except IndexError:
print("Index out of range.")

def set(age):

if age < 0:

raise ValueError("Age cannot be negative.")

print(f"Age set to {age}")

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:

raise ExceptionType(“Error message”)


def set(age):

if age < 0:

raise ValueError("Age cannot be negative.")

print(f"Age set to {age}")

try:

set(-5)

except ValueError as e:
print(e)

You might also like