UNIT 4 (File Handling and Exception Handling)
UNIT 4 (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.
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
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()
['Python: \n', 'Python is an interactive Programming Language.\n', ' Hello \n', 'World \n', 'One \n', 'two']
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
Python:
Python is an interactive Programming Language.
Hello
World
One
two
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()
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()
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
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.
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.
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
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)
In [14]: main()
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
In [3]: main()
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
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()
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()
In [9]: main()
In [36]: main()
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()
In [39]: main()
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
In [18]: main()
Thank you
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[18], line 1
----> 1 main()
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 [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