unit6
unit6
INTRODUCTION
A file is a collection of related data that acts as a container of storage data permanently.
The file processing refers to a process in which a program processes and accesses data stored in files.
A file is a computer resource used for recording data in a computer storage device.
The processing on a file is performed using read/write operations performed by programs.
Python supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.
Python programming provides modules with functions that enable us to manipulate text files and
binary files.
Python allows us to create files, update their contents and also delete files.
A text file is a file that stores information in the term of a sequence of characters (textual
information), while a binary file stores data in the form of bits (Os and 1s) and used to store
information in the form of text, images, audios, videos etc.
Syntax:
print (object(s),separator=separator, end=end, file=file, Flush= Flush)
Parameter values.
object(s): It can be any object but will be converted to string before printed.
seperator='separator': Optional. Specify how to separate the objects, if there is more than one.
Default is’’ .
end='end’optional. Specify what to print at the end. Default is (line feed).
file= Optional An object with a write method.
File IO handling and Exception Handling Unit 6
flush.: Optional,A.Boolean, specifying if the output is flushed (True) or buffered (False). Default
is False.
To make the output more attractive formatting is used. This can be done by using the str.formatO
method..
Just like old print style used in C programming language, we can format the output in Python
language also. The % operator is used to accomplish this.
1 %c Character.
2 %s String conversion via strO prior to formatting_
3 %i Signed decimal integer.
4 %d Signed decimal integer.
5 %u Unsigned decimal integer.
6 %o Octal integer.
7 %x Hexadecimal integer (lowercase letters).
8 %X Hexadecimal integer (Uppercase letters).
File IO handling and Exception Handling Unit 6
Syntax; input(prompt)
output:
Enter your name:abc
Hello, abc.
(ii) input(): The function input always evaluate the input provided by user and return same type
data
The syntax is as follows,
Syntax:
x=input()
If input value is integer type then its return integer value. If input value is string type then its return
string value.
Example: For reading input from keyboard.
>>> x=input()
5
>>> type(x)
<class 'int'›
x=input()
5.6
>>> type(x)
<class '.Float'>
>>> x=int(input())
5
File IO handling and Exception Handling Unit 6
a>> type(x)
<class 'int' >
>> x=float(lnput())
2.5
>>> type(x)
<class ' float' >
File
File is a named location on disk to store related information. It is 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 computer is turned
OFF, we use files for future use of the data.
Files are divided into following two categories:-
Text Files: Text files are simple texts in human readable format. A text file is structured as sequence
of lines of text,
Binary Files: Binary files have binary data (Os and is) which is understood by the computer.
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 resources that are tied with the file are freed.
If the file resides in a directory other than PWD, we have to provide the full path with the file
name:
>>>File=open(“D:\\Files\abc.txt)
>>>File.read()
'Hello I am there’
>>>
We can specify the mode while opening a file. In mode, we specify whether we want to read write
'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file. The
binary mode returns bytes and this is the mode to be used when dealing with non-text files like image
or exe Files.
The mode of the file specifies the possible operations that can be performed on the file what
purpose we are opening a file.
Apart from this, two other modes exist, which specify to open the file in
● text mode or
● Binary mode.
● The text mode returns strings while reading from the file.The default is reading in text
mode.
● The binary mode returns bytes and this is the mode to be used when dealing with non-text
files like image or executable files.
The text and binary modes are used in conjunction with the r, w, and a modes. The list of all the
modes used in Python are given in following table:
2 rb Opens a file for reading only in binary format. The file pointer is placed
at the beginning of the file. This is the default mode.
3 r+ Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.
4 rb+ Opens a file for both reading and writing in binary format. Tice file
pointer placed at the beginning of the file.
5 w Opens a rile for writing only. overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
6 wb Opens a file for writing only irk binary format. Overwrites the file if the
file exists. If the file does not exist, creates a new file for writing_
7 w+ Opens a file for both 'writing and reading. Overwrites the existing file if
the file exists. If the file does riot exist, creates a new file for reading
and writing.
8 Wb+ Opens a file for both writing and reading in binary format. Overwrites the
existing file if the file exists. If a file does not exist. creates a new file for
writing.
9 a. opens a file for appending in binary format. The file pointer Is at the
end of the file. If the file exists That is to be append mode.If the file
does not exit it creates a file for writing.
12 ab+ Opens file for both appending and reading in binary format
Sr.N
o Description Example
Output:
Sample.txt
R
Cp1252
True
Closing File
When we are done with operations to the file, we need to properly close the file.Closing a file will free
up the resources that were tied with the file and is done using Python close() method.
Syntax: FileObject.close( )
Output
Name of the File: sample.txt
f.open("sample.txt”)
print(“content of file”)
print(f.read())
f.open(“sample.-txt",'"w")
f..write(“first line\n”)
f..write(“second line\n”)
f..write(“Third line\n”)
f.close()
f.open("sample.txt”)
print(“content of file”)
print(f.read())
Output:
content of file Hello,1
am There
content of file1. first
line
second line
third line
File IO handling and Exception Handling Unit 6
writelines(list) Method:
It writes a sequence of strings to the file. The sequence can be any iterable object
producing strings. typically a list of strings. There is no return value.
fruits=["Orange\n","Banana\n","Apple\n”]
f=open("sample_txt",mode="w")
f.writelines(fruits)
f.close()
f.open("sample_txt",'"r")
print(f.read())
output
Orange
Banana
Apple
Read ( ): Returns the read bytes in the form of a string. Reads n bytes; if n is not specified, then
reads the entire file.
Readline ( ): Reads a line of the file and returns in the form of a string. For specified n, reads at
most n bytes. readline ( ) function does not read more than one line at a time; even if n exceeds, it
reads only one line. Readline ( ) function reads a line of the file and returns it in the string. It takes
an integer value n as a parameter to read the number of characters read at a time. Readline ( ) method
is very efficient in reading the data from a very large file because it fetches the data line by line and
returns and prints on the screen. Readline ( ) returns the next line of the file, which contains a newline
character in the end. Also, if the end of the file is reached, it will return an empty string.
readlines ( ): Reads all the lines and returns them as a string element in a list. Readlines ( ) is used
to read all the lines at a single go and then return them as a string element in a list. This function can
be used for small files, as it reads the whole file content to the memory, then splits it into separate
lines. Using the strip () function, we can iterate over the list and strip the newline ' \n ' character
using the strip ( ) function.
Output:
First
line
Second Line
third Line
output:
[ 'first line, 'second line\n', 'third line\n']
File Position
● We can change the current file cursor (position) using the seek0 method. Similarly,
the tell() method returns the current position (in number of bytes) of file
cursor/pointer.
● To change the file object's position use f.seek(offset, reference_point). The position
is computed from adding offset to a reference point.
● The reference point can be omitted and defaults to 0, using the beginning of the file
as the reference point. The reference points are 0 (the beginning of the file and is
default), 1 (the current position of file) and 2 (the end of the file).
● The f.tell() returns an integer giving the file object's current position in the file
represented as number of bytes from the beginning of the file when in binary mode
and an opaque number when in text mode.
In other words, the tell() is used to find the current position of the file pointer in the file while
the seek() is used to move the file pointer to particular position.
Output:
0
first line
second line
third line
37
0
first line
second line
third line
>>>
Example 2:
fruits=["0range\n'imBanana\n","Apple\e]
f=open("sample_txt",mode"w4-",encodinp"utf-8")
for fru in fruits:
f.write(fru)
print("Tell the byte at which the file cursor is:",f.tell())
f.seek(0)
for line in f:
print(line)
Output:
Tell the byte at which the file cursor is7. 23
Orange Banana Apple
try:
Returns the next line from the last while f.next():
5 File.next()
upset Print(f.next)
exception:
This function reads the entire file Lines=f.read()
6 file.read()
and returns a string. f.write(lines)
Lines=f.read(10)
7 file.read(size) Reads the given number of bytes.
print(lines)
file.readline() Reads a single line and returns it Lines=f.readline()
8
as a string. print(lines)
file.readline(size) It will read an entire line (trailing Lines=f.readline(10)
9
with a new line char) from the print(lines)
Reads the content of a file line by lines =f.readlines()
10 file.readlines()
line and returns them as a list of f.writelines(lines)
It calls the readline() to read until text =f.readlines(25)
11 File.readlines(sizehint)
EOF. It returns a list of lines read print(text)
position =f.seek(0,0);
12 file.seek(offset[,from]) Sets the file's current position. print(position)
f.close()
lines =read(10)
13 file.tell() Returns the file's current position. #tell()
print(f.tell())
truncates the file's size. If the f.truncate(10)
14 file.truncate(size)
optional size argument is present, f.close()
It writes a string to the file. And it line ='welcome Geeks\n'
15 file.write(string) f.write(line)
doesn't return any value.
Writes a sequence of strings to f.close()
lines =f.readlines()
16 file.writelines(sequence)
the file. The sequence is possibly f.writelines(lines) f.close()
Output:
File IO handling and Exception Handling Unit 6
Line one Line two Line three
Is readable! True
Is writeable: True
File no: 3
Is connected to tty-like device: False
Sr. Description
Function Example
No
2 os.path.getsize() Show file size in bytes of file passed in size =os.path.getsize("sample . txt")
parameter.
3 os.path.isfile() print(os.path.is.file("sample.trt"))
Is passed parameter a file.
8
os.remove(flle name) Delete a file. os.remove("sample.txt")
File IO handling and Exception Handling Unit 6
9
0s.mkdir() Creates a single subdirectory. os.madir("testdir")
output
True
False
Renaming a File
Renaming a file in Python is done with the help of the rename() method. To rename a file in Python,
the OS module needs to be imported.The rename() method takes two arguments, the current filename
and the new filename.
Deleting a File
We can use the remove() method to delete files by supplying the name of the file to be deleted as
the argument.To remove a file, the OS module need to be imported. The remove in Python
programming in used to remove the existing file with the file name.
Syntax:
os.remove(file_name)
The is file0 method in Python programming checks whether the file passed in the method exists or
not. It returns true if the file exist otherwise it returns false.
Directories
If there are a large number of files to handle in the Python program, we can arrange the code within
different directories to make things more manageable.
A directory or folder is a collection of files and sub directories. Python has the os module, which
provides us with many useful methods to work with directories (and files as well).
Example:
>>> import os
>>> os.getcwd()
'C:\users\\ vaishali\\AppData\\Loca1\\Programs\%Python\\Python37-32'
Changing Directory
We can change the current working directory using the chdir() method.The new path that we want
to change must be supplied as a string to this method. We can use both forward slash (F) or the
backward slash (x) to separate path elements.
syntax:
os.chdir("dirname")
Example:
>>> Import os
>>> os.getcwd()
'CA\Users\\vaishali\\AppDataNALocal\\Programs\Wython\Vython371
>>> os.chdir(“d:\IT”)
>>> os.getcwd()
'd:\\IT'
EXCEPTION HANDILNG
When we execute a Python program, there may be a few uncertain conditions which occur, known
as error. Errors also referred to as bugs that are incorrect or inaccurate action that may cause the
problems in the running of the program or may interrupt the execution of program.
Compile Time Errors: Occurs at the time of compilation, include due error occur to the violation
of syntax roles, like missing of a Color (:)
Run Time Errors: Occurs during the runtime of a program, example, include error occur due to
Wong input submitted to program by user.
Logical Errors: Occurs due to wrong logic written in the program.
● Errors occurs at runtime are known as exception, Errors detected during execution of
program. Python provides a feature. (Exception handling) for handling any unreported
errors in program.
● When exception occurs in the program, execution gets terminated. In such cases we get
system generated error message.
● By handling the exceptions, we can provide a meaningful message to the user about the
problem rather than system generated error message, which may not be understandable to
the user.
● Exception can be either built-in exceptions or user defined exceptions.
● The interpreter or built-in functions cart generate the built-in exceptions while user defined
exceptions are custom exceptions created by the user.
Introduction
● An exception is also called as runtime error that can halt the execution of the program.
● An exception is an error that happens/occurs during execution of a program_ When that error
occurs. Python generate an exception that can be handled, which avoids the normal flow of
the program's Instructions.
● Errors detected during execution are called Exceptions. An exception is an event (usually an
error).
● which occurs during the execution of a program that disrupts the normal flow of execution
of the program (or program's instructions).
● In Python programming we can handle exceptions using try-except statement, try-finally
statement and raise statement.
Following table lists all the standard exceptions available in Python programming language:
SR
. Exception Causes of Error
No
1 ArithematicError base class for all errors that occur for numeric calculation.
3 EOFError Raised when there is no input from either the raw_input() or input function and the end of
file Is reached.
9 KeyError Raised when the specifled key Is not found in the dictionary.
11 NameError Raised when an identifier is not found in the local or global namespace.
File IO handling and Exception Handling Unit 6
12 NotImplmentedError Raised when an abstract method that needs to be implemented in an inherited class is not
actually implemented.
15 RuntimeError Raised when a generated error does not fall into any category.
16 StopIteration Raised when the next method of an iterator does not point to any object.
StandardError Base class for all built-in exceptions except Stop iteration and SystemExit.
18
TypeError Raised when an operation or function is attempted that is invalid for the specified data
21 type.
Raised when the built in function for a data type has the valid type of arguments, but the
22 ValueError
arguments have invalid values specified
23 Raised when division or module by zero takes place for all numeric type
ZeroDivisionError
The associated except blocks are used to handle any resulting exceptions thrown in the try
block.
If any statement within the try block throws an exception, control immediately shifts to the
catch block. If no exceptions is thrown in the try block, the catch block is skipped.
There can be one or more except blocks. Multiple except blocks with different exception
names can be chained together.
The except blocks are evaluated from top to bottom in the code, but only one except block is
executed for each exception that is thrown.
The first except block that specifies the exact exception name of the thrown exception is
executed. If no except block specifies a matching exception name then an except block that
does not have an exception name is selected, if one is present in the code.
Syntax:
try:
certain operations here
----------------------
except Exceptionl:
If there is Exceptionl, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
--------------------------------
else:
If there is no Exception,then execute this block.
raise Statement
We can raise an existing exception by using raise keyword. So, we just simply write raise
keyword and then the name of the exception. The raise statement allows the programmer to
force a specified exception to occur.
Example: We can use raise to throw an exception if age is less than 18 condition
occurs.
while True:
try:
age = int(input("Enter your age for election: " ) )
if age < 18:
raise Exception
else:
print ("you are eligible for election")
break
except Exception:
print(“This value is too small, try again”)
Output.
Enter your age for election:
This value is too small, try again
Enter your age for election: 18
you are eligible for election
▪ The raise statement can be complemented with a custom exception as explained in next section.
User Defined Exception
Python has many built-in exceptions which forces the program to output an error when
something in it goes wrong. However, sometimes we may need to create custom exceptions
that serves the purpose.
▪ Python allow programmers to create their own exception class_ Exceptions should typically
be derived from the Exception class, either directly or indirectly. I-lost of the built-in
exceptions are also derived from Exception class.
User can also create and raise his/her own exception known as user defined exception.
File IO handling and Exception Handling Unit 6
In the following example, we create custom exception class AgeSmallException that is
derived from the base class Exception.
Example 1: Raise a user defined exception if age is less than 18. 4 define Python user-
defined exceptions
Output:
Enter your age for election: 11
This value is too small, try again!
Enter your age for election: 15
This value is too small, try again!
Enter your age for election: 18
You are eligible for election