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

UNIT 4 (File Handling and Exception Handling)

The document provides an overview of file handling and exception handling in Python. It details various file operations such as opening, reading, writing, and closing files, as well as handling exceptions using try-except blocks. Common exceptions like NameError, TypeError, and ZeroDivisionError are also discussed, along with examples of how to manage errors effectively.

Uploaded by

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

UNIT 4 (File Handling and Exception Handling)

The document provides an overview of file handling and exception handling in Python. It details various file operations such as opening, reading, writing, and closing files, as well as handling exceptions using try-except blocks. Common exceptions like NameError, TypeError, and ZeroDivisionError are also discussed, along with examples of how to manage errors effectively.

Uploaded by

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

File Handling and Exception Handling 26/12/24, 12:15 PM

File Handling and Exception Handling

File Handling
A file is a stream of bytes.
File can be used in any application where data is required to be stored permanently.
The functions to perform operations on file are as follows:

open(file_name, access_mode)
To open the file in a specific mode.
It takes two arguments: file_name and access_mode.
The access_mode can be Read(r), Write(w), Append(a), Read and Write both(r+).
The default access_mode is Read(r).
While opening the file in read mode, if the file does not exist, it would lead to an error.
While opening the file in write mode, if the file does not exist, a new file will be created.
While opening the file in write mode, if the file already exist, the file gets overwritten.
With the help of append mode, we can add data to an existing file.
Successful execution of open() function, returns a file object.
This file object is used to call the pre-defined functions of the file.

write( )
is used to write content in the file.
when user calls the write() function, it writes the content in the file and returns the number of characters written into the file.

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 1 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

writelines( )
It takes a list of lines (as an argument) to be written in the file.
The list of lines can be any sequence (string, list, set and tuple).

read( )
is used to read the content from the file.
read() function reads all the content at once from the file.
However, we can specify as argument, the number of characters (an integer value), we want to read from the file.

readline( )
this function read one line at a time from the file.

readlines( )
reads multiple lines from the file and return in the form of a list.
can be executed after execution of readline() function, to read remaining lines of the file.

close( )
When a file is no longer required for reading or writing, it should be closed.
clsoe() function saves the file and close it.

tell( )
is used to know the current position (index of file content character) of file object.

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 2 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

seek( )
When all the contents of a file have been read, a further read operation on it will return a null string.
To read from a particular position in a file, seek() function can be used.
For example, to read from the beginning of the file, call the seek() function with the argument 0, seek(0).
Zero here denotes the index of first character of the file.

Using 'with' statement for opening the file


We can perform file operations after opening the file using 'with' statement.
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.

In [1]: def main():


f = open("/Users/hunnygaur/Desktop/UNIT 4/File4.txt", 'w')
heading = "About File Handling \n"
description = ["Python: \n", "Python is an interactive Programming Language."]
tuple1 = ("\n Hello \n", "World \n")
set2 = {'One \n', 'two'}
f.write(heading)
f.writelines(description)
f.writelines(tuple1)
f.writelines(set2)
f.close()
f = open("/Users/hunnygaur/Desktop/UNIT 4/File4.txt", 'r')
print(f.read())
f.close()

In [2]: main()

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 3 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

About File Handling


Python:
Python is an interactive Programming Language.
Hello
World
One
two

In [4]: # Using readline() and readlines() function to read content of the file.

def main():
f = open("/Users/hunnygaur/Desktop/UNIT 4/File4.txt", 'r')
print(f.readline())
print(f.readlines())
f.close()

In [5]: main()

About File Handling

['Python: \n', 'Python is an interactive Programming Language.\n', ' Hello \n', 'World \n', 'One \n', 'two']

In [6]: # Converting data read from readlines() function into a string.

def main():
f = open("/Users/hunnygaur/Desktop/UNIT 4/File4.txt", 'r')
print(f.readline())
data = f.readlines()
print(''.join(data))
f.close()

In [7]: main()

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 4 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

About File Handling

Python:
Python is an interactive Programming Language.
Hello
World
One
two

In [8]: # Example: Program to copy content of one file into another.

def main():
f1 = open("/Users/hunnygaur/Desktop/UNIT 4/File1.txt", 'r')
f2 = open("/Users/hunnygaur/Desktop/UNIT 4/File2.txt", 'w')
data = f1.read()
f2.write(data)
f1.close()
f2.close()

In [9]: main()

In [10]: # Using with statement for opening the file.

def main():
with open("/Users/hunnygaur/Desktop/UNIT 4/Demo.txt", 'w') as f:
f.write("This is Demo File for testing File Handling code")
with open("/Users/hunnygaur/Desktop/UNIT 4/Demo.txt", 'r') as f:
print(f.read())

In [11]: main()

This is Demo File for testing File Handling code

Exception Handling
file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 5 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

Error occurs when something goes wrong.


The errors in Python programming may be categorized as Syntax errors and Exceptions.
Exception occurs because of some mistake in the program that the system cannot detect before executing the code.
This error will lead to a situation during execution that system cannot handle.
Whenever an exception occurs, a Traceback object is displayed which includes error name, its description and the point of
occurrence of the error such as line number.

Commonly Encountered Exceptions


NameError
Whenever a name that appears in a statement is not found globally.
For example, using a variable without initializing it.

TypeError
When an operation or function is applied to an object of inappropriate type.
For example, adding string with number.

ValueError
Whenever an inappropriate argument value (even though of correct type) is used in the function call.
For example, usinng int() function to convert string to integer, int('Hello')

ZeroDivisionError
When user try to perform. numeric division in which denominator happens to be zero.
For example, 78/(2+3-5)

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 6 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

OSError
Whenever there is a system related error such as disk full or an error related to input/output.
for example, opening a non-existent file for reading or readiing a file opened in write mode.

IndexError
Whenever we try to access an index that is out of a valid range.

Handling Exceptions using Try.....Except


To prevent a program from terminating abruptly when an exception is raised, handle it by catching it and taking appropriate
action using try....except clause (block).

Try block
comprises statements that have the potential to raise an exception.

Except block
describes the action to be taken when an exception is raised.

Finally block
is executed irrespective of whether an exception is raised or not.

In [17]: def main():


x = 10
try:

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 7 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

print(x)
f = open("/Users/hunnygaur/Desktop/UNIT 4/test.txt", 'r')
print(f.read())
f.close()
except IOError:
print("File does not exist")
except NameError:
print("Assign some value to the variable before printing it")
print("Program continues smoothly after try...except block")
main()

10
File does not exist
Program continues smoothly after try...except block

In [13]: f = open("/Users/hunnygaur/Desktop/UNIT 4/test.txt", 'r')


print(f.read())
f.close()
print("Hello")

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 8 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[13], line 1
----> 1 f = open("/Users/hunnygaur/Desktop/UNIT 4/test.txt", 'r')
2 print(f.read())
3 f.close()

File /Applications/opt/anaconda3/anaconda3/lib/python3.12/site-packages/IPython/core/interactiveshell.py:324, in
_modified_open(file, *args, **kwargs)
317 if file in {0, 1, 2}:
318 raise ValueError(
319 f"IPython won't let you open fd={file} by default "
320 "as it is likely to crash IPython. If you know what you are doing, "
321 "you can use builtins' open."
322 )
--> 324 return io_open(file, *args, **kwargs)

FileNotFoundError: [Errno 2] No such file or directory: '/Users/hunnygaur/Desktop/UNIT 4/test.txt'

In [14]: main()

File does not exist


Program continues smoothly after try...except block

In [1]: f = open("/Users/hunnygaur/Desktop/UNIT 4/test1.txt", 'w')


f.write("This is Python File Handling Unit. \n Next unit will be about Numpy and Pandas library.")
f.close()

In [2]: def main():


try:
f = open("/Users/hunnygaur/Desktop/UNIT 4/test1.txt", 'r')
print(f.read())
f.close()
print(3/0)
except IOError:

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 9 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

print("File does not exist")


print("Program continues smoothly after try...except block")

In [3]: main()

This is Python File Handling Unit.


Next unit will be about Numpy and Pandas library.
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[3], line 1
----> 1 main()

Cell In[2], line 6, in main()


4 print(f.read())
5 f.close()
----> 6 print(3/0)
7 except IOError:
8 print("File does not exist")

ZeroDivisionError: division by zero

In [20]: def main():


try:
f = open("/Users/hunnygaur/Desktop/UNIT 4/test1.txt", 'r')
print(f.read())
f.close()
print(3/0)
except:
print("File does not exist")
print("Program continues smoothly after try...except block")

In [21]: main()

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 10 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

This is Python File Handling Unit.


Next unit will be about Numpy and Pandas library.
File does not exist
Program continues smoothly after try...except block

In [4]: # Example: Specifying multiple types of errors together

def main():
price = input("Enter the price of the item purchased: ")
weight = input("Enter the weight of the item purchased: ")
try:
if price == '':
price = None
price = float(price)
if weight == '':
weight = None
weight = float(weight)
assert price >= 0 and weight >= 0
result = price/weight
except (ValueError, TypeError, ZeroDivisionError):
print("Invalid input provided by the user.")
else:
print("Price per unit weight: ", result)

In [6]: main()

Invalid input provided by the user.

In [7]: import sys

def main():
price = input("Enter the price of the item purchased: ")
weight = input("Enter the weight of the item purchased: ")
try:
if price == '':
price = None

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 11 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

price = float(price)
if weight == '':
weight = None
weight = float(weight)
assert price >= 0 and weight >= 0
result = price/weight
except (ValueError, TypeError, ZeroDivisionError):
print("Invalid input provided by the user. \n" + str(sys.exc_info()))
else:
print("Price per unit weight: ", result)

In [8]: main()

Invalid input provided by the user.


(<class 'ZeroDivisionError'>, ZeroDivisionError('float division by zero'), <traceback object at 0x1053bbd80>)

In [9]: main()

Invalid input provided by the user.


(<class 'TypeError'>, TypeError("float() argument must be a string or a real number, not 'NoneType'"), <traceback
object at 0x104b44400>)

In [36]: main()

Enter the price of the item purchased: 23


Enter the weight of the item purchased: 12
Price per unit weight: 1.9166666666666667

In [14]: # Example: Specifying multiple types of errors separately

import sys

def main():
price = input("Enter the price of the item purchased: ")
weight = input("Enter the weight of the item purchased: ")
try:

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 12 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

if price == '':
price = None
price = float(price)
if weight == '':
weight = None
weight = float(weight)
assert price >= 0 and weight >= 0
result = price/weight
#print(x)
except ValueError:
print("Invalid input provided by the user: ValueError")
except TypeError:
print("Invalid input provided by the user: TypeError")
except ZeroDivisionError:
print("Invalid input provided by the user: ZeroDivisionError")
except:
print(str(sys.exc_info()))
else:
print("Price per unit weight: ", result)

In [15]: main()

Price per unit weight: 28.0

In [39]: main()

Enter the price of the item purchased: 23


Enter the weight of the item purchased: 0
Invalid input provided by the user: ZeroDivisionError

In [16]: # Example: Using finally block

def main():
marks = int(input("Enter marks"))
try:
if marks < 0 or marks > 100:

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 13 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

raise ValueError("Marks out of range")


finally:
print("Thank you")
print("Program continues after handling exception")

In [18]: main()

Thank you
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[18], line 1
----> 1 main()

Cell In[16], line 7, in main()


5 try:
6 if marks < 0 or marks > 100:
----> 7 raise ValueError("Marks out of range")
8 finally:
9 print("Thank you")

ValueError: Marks out of range

In [46]: def main():


marks = int(input("Enter marks"))
try:
if marks < 0 or marks > 100:
raise ValueError()
finally:
print("Thank you")
print("Program continues after handling exception")

In [48]: main()

Enter marks102
Thank you

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 14 of 15
File Handling and Exception Handling 26/12/24, 12:15 PM

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/var/folders/71/9p4hsdf14knb5ss7tsgbyd7m0000gn/T/ipykernel_974/451043146.py in <module>
----> 1 main()

/var/folders/71/9p4hsdf14knb5ss7tsgbyd7m0000gn/T/ipykernel_974/699336362.py in main()
3 try:
4 if marks < 0 or marks > 100:
----> 5 raise ValueError()
6 finally:
7 print("Thank you")

ValueError:

In [49]: def main():


marks = int(input("Enter marks"))
try:
if marks < 0 or marks > 100:
raise ValueError()
finally:
print("Thank you")
print("Program continues after handling exception")

In [50]: main()

Enter marks98
Thank you
Program continues after handling exception

In [ ]:

file:///Users/hunnygaur/Downloads/File%20Handling%20and%20Exception%20Handling.html Page 15 of 15

You might also like