PYTHON UNIT-3
PYTHON UNIT-3
Files are named locations on disk to store related information. They are used to
permanently store data in a non-volatile memory (e.g. hard disk). Since Random Access
Memory (RAM) is volatile (which loses its data when the computer is turned off), we use
files for future use of the data by permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed so that the resources that are tied with the file are freed.
Absolute path
Always contains the root and the complete directory list to specify the exact
location of the file
Relative Path
Is specified relative to the program’s current working directory
Python has a built-in open() function to open a file. This function returns a file object,
also called a handle, as it is used to read or modify the file accordingly.
In this mode, we get strings when reading from the file. On the other hand, binary
mode returns bytes and this is the mode to be used when dealing with non-text files like
images or executable files.
AVCCE/MCA/R-21/I-SEM/NS Page 1
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Mode Description
Opens a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
Opens a file for appending at the end of the file without truncating it. Creates a new
a
file if it does not exist.
The character a does not imply the number 97 until it is encoded using ASCII (or other
equivalent encodings). the default encoding is platform dependent. In windows, it
is cp1252 but utf-8 in Linux.
So, we must not also rely on the default encoding or else our code will behave differently in
different platforms.
AVCCE/MCA/R-21/I-SEM/NS Page 2
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Hence, when working with files in text mode, it is highly recommended to specify the
encoding type.
f = open("test.txt", mode='r', encoding='utf-8')
When we are done with performing operations on the file, we need to properly close the
file. Closing a file will free up the resources that were tied with the file. It is done using
the close() method available in Python. Python has a garbage collector to clean up unreferenced
objects but we must not rely on it to close the file.
f = open("test.txt", encoding = 'utf-8') # perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some
operation with the file, the code exits without closing the file. A safer way is to use
a try...finally block.
3.4.1 try...finally
try:
f = open("test.txt", encoding = 'utf-8') # perform file operations
finally:
f.close()
This way, we are guaranteeing that the file is properly closed even if an exception is raised
that causes program flow to stop. The best way to close a file is by using the with statement. This
ensures that the file is closed when the block inside the with statement is existed. We don't need to
explicitly call the close() method. It is done internally.
Writing a string or sequence of bytes (for binary files) is done using the write() method.
This method returns the number of characters written to the file.
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
This program will create a new file named test.txt in the current directory if it does not exist.
If it does exist, it is overwritten. We must include the newline characters ourselves to distinguish
the different lines.
AVCCE/MCA/R-21/I-SEM/NS Page 3
MC4103_Python Programming Unit -3| File Handling And Exception Handling
We can read a file line-by-line using a for loop. This is both efficient and fast.
f = open("test.txt",'r',encoding = 'utf-8')
>>> for line in f:
print(line, end = '')
This is my first file
This file
contains three lines
In this program, the lines in the file itself include a newline character \n. So, we use the
end parameter of the print() function to avoid two newlines when printing. Alternatively, we can
use the readline() method to read individual lines of a file. This method reads a file till the
newline, including the newline character.
>>> f.readline() 'This is my first file\n'
>>> f.readline() 'This file\n'
>>> f.readline() 'contains three lines\n'
>>> f.readline()
''Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
methods return empty values when the end of file (EOF) is reached.
>>> f.readlines() ['This is my first file\n', 'This file\n', 'contains three lines\n']
AVCCE/MCA/R-21/I-SEM/NS Page 4
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Method Description
close() Closes an opened file. It has no effect if the file is already closed.
Separates the underlying binary buffer from the TextIOBase and
detach()
returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
Reads at most n characters from the file. Reads till end of file if it is
read(n)
negative or None.
readable() Returns True if the file stream can be read from.
Reads and returns one line from the file. Reads in at most n bytes if
readline(n=-1)
specified.
Reads and returns a list of lines from the file. Reads in at most n
readlines(n=-1)
bytes/characters if specified.
Changes the file position to offset bytes, in reference to from (start,
seek(offset,from=SEEK_SET)
current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
Resizes the file stream to size bytes. If size is not specified, resizes to
truncate(size=None)
current location.
writable() Returns True if the file stream can be written to.
Writes the string s to the file and returns the number of characters
write(s)
written.
writelines(lines) Writes a list of lines to the file.
The program that we write may behave abnormal or unexpectedly because of some errors
and exceptions. An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception.
An exception is a Python object that represents an error. When a Python script raises an
exception, it must either handle the exception immediately otherwise it terminates and quits.
AVCCE/MCA/R-21/I-SEM/NS Page 5
MC4103_Python Programming Unit -3| File Handling And Exception Handling
– Syntax errors- it occur due to poor understanding of the language. Or violate the rules of
python
>>> i=0
>>> if i==0 print(i)
SyntaxError: invalid syntax
– Logic errors- it occur due to poor understanding of the problem and its solutions. It leads
to run-time a error, that causes the program to terminate abruptly. The following are some
examples of runtime errors.
3.8 Exceptions :
Exceptions are run-time anomalies or unusual conditions that a program may encounter
during the execution. (such as divide by zero, accessing arrays out of its bounds, running out of
memory or disk space, overflow, and underflow)
• Asynchronous Exceptions – caused by the events that are beyond the control of the
program.
AVCCE/MCA/R-21/I-SEM/NS Page 6
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Exception handling is a mechanism which allows us to handle errors gracefully while the
program is running instead of abruptly ending the program execution. We can handle exceptions
in our program by using try block and except block. A critical operation which can raise
exceptions is placed inside the try block. The code that handles exceptions is written in except
block. Its syntax is as follows:
try:
# try block
# write code that might raise an exception here
<statement_1>
<statement_2>
except ExceptiomType:
# except block
# handle exception here
<handler>
try:
write code here
except Exception1:
if exception1 occurs then execute this code
except Exception2:
if exception2 occurs then execute this code
….
….
else:
if there is no exception then execute this code
AVCCE/MCA/R-21/I-SEM/NS Page 7
MC4103_Python Programming Unit -3| File Handling And Exception Handling
3.8.2.1. Try –except: The try and except statements are used to handle runtime errors
Syntax:
try:
statements
except :
statements
AVCCE/MCA/R-21/I-SEM/NS Page 8
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Example
X=int(input("Enter the value of X"))
Y=int(input("Enter the value of Y"))
try:
sum= X + Y
divide = X / Y
print ("Sum of {} and {} ={}".format(X,Y,sum))
print ("Division of {} and {} = {}".format(X,Y,divide))
except NameError:
print("The input must be number")
except ZeroDivisionError:
print("Division by Zero")
Output:
Enter the value of X 6
Enter the value of Y0
Division by Zero
• The else part will be executed only if the try block does not raise the exception.
• Python will try to process all the statements inside try block.
• If value error occur, the flow of control will immediately pass to the except block and
remaining statements in try block will be skipped.
Syntax:
try:
statements
except:
statements
else:
statements
AVCCE/MCA/R-21/I-SEM/NS Page 9
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Syntax:
try:
statements
except:
statements
finally:
statements
AVCCE/MCA/R-21/I-SEM/NS Page 10
MC4103_Python Programming Unit -3| File Handling And Exception Handling
Example
x=int(input("Enter the value of X"))
y=int(input("Enter the value of Y"))
try:
result=x/(x-y)
except ZeroDivisionError:
print("Division by Zero")
else:
print("result=",result)
finally:
print ("Program completed")
***** SUCCESS!*****
AVCCE/MCA/R-21/I-SEM/NS Page 11