Python Notes
Python Notes
================================================
UNIT-6 File I/O Handling and Exception Handling
================================================
***Files***
- File is a collection of related records.
- File is used to store the records permanently.
- File is used to store and access records.
- File is computer resource user for recording data in computer
storage device.
- Processing on file is performed using read/write operations.
- Python supports file handling and allows user to handle file.
- We can perform many operations on file like creating file, updating
file, deleting file, etc.
- There are two different types of file
1) Text Files:
- Text files are simple text in human readable format. It is collection
of sequence of text.
2) Binary Files:
- Binary files have binary data i.e 0s and 1s which is understood by
the computer.
- We follow below orders while working with file:
I) Open a File.
II) Read or Write Files.
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-6 File I/O Handling and Exception Handling
- Example:
file=open("vjtech.txt",'w');
- In above example vjtech.txt file opens in writing mode.
✓ Closing File:
- When we are done with all operations to the file then we need to
properly close the file.
- Closing the file will free up the resources that allocated by the file.
- Syntax:
fileobject.close();
==========================
Writing Data to a File:
==========================
- We use write() function to write string in file.
- If we want to write some contents into a file then we have to open
the file in "w" or "a" mode.
- The write() method writes the contents onto the file. It takes only
one parameter and returns the number of characters writing to the
file.
- If we open the file in "w" mode then contents of the file got
override.
- And if we open the file in "a" mode then new contents added at
last.
- There are two different write() methods available for write the
data.
1)write(string):
- This method write contents of string to the file and return no of
characters written.
- Example:
#write data into a file using write() method
f1=open("vjtech.txt","w");
f1.write("This is Python Language\n");
f1.write("This is Object Oriented Programming Language\n");
f1.write("We are learning this language in VJTech Academy");
print("Data written successfully in file!!!");
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-6 File I/O Handling and Exception Handling
f1.close();
2) writelines(list):
- It writes sequence of strings to the file and there is no any return
value.
- Example:
#write data into file using writelines() method.
f1=open("sample.txt","w");
msg=["VJTech Academy\n","MSBTE\n","Maharashtra\n","Pune\n"];
f1.writelines(msg);
print("Data written successfully into the file!!!");
f1.close();
==========================
Reading Data from File:
==========================
- To read a file in python, we must open the file in reading mode("r"
or"r+").
- The read() method in python reads contents of the file.
- This method returns the characters read from the file.
- There are three different read() methods available for read the
data.
1) read([n]):
- This method read the complete contents of the file if you have not
specified n value.
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-6 File I/O Handling and Exception Handling
- But if you given the value of n then that much of characters read
from the file. For example, suppose we have given read(3) then we
will get back the first three characters of the file.
- Example:
#read contents of the file using read() method
f1=open("vjtech.txt","r");
print(f1.read(5)); #read first 5 data
print(f1.read(10)); #read next 10 data
print(f1.read()); #read rest of the file data
2) readline([n]):
- This method just output the entire line.
- But if we spcify the value of n then it will return n bytes of single
line of the file.
- This method does not read more than one line.
- Example:
#read contents of the file using readline() method
f1=open("sample.txt","r");
print(f1.readline()); #read first line
print(f1.readline(3)); #read first three character of line
print(f1.readline(4)); #read next 4 characters of the line
3) readlines():
- This method is used to read complete lines of the file.
- Example:
#read contents of the file using readlines() method
f1=open("sample.txt","r");
print(f1.readlines()); #read complete lines of the file
-Output:
['VJTech Academy\n', 'MSBTE\n', 'Maharashtra\n', 'Pune\n']
==============
File Position
==============
- We can change the position of file cursor using seek() method.
- tell() will return the current position of file cursor.
- Syntax:
f.seek(offset,reference_point);
- The position is computed from adding offset to a reference point.
- Reference point can be ommited and default to 0.
- Following values we can use for reference point.
I) 0 : beginning of the file
II) 1 :current position of the file
III) 2: end of the file.
- tell() method is used to find the current position of the file pointer
in the file.
=================
Renaming the file
=================
- Renaming the file in python is done with the help of rename()
method.
- To rename a file in python, the os module needs to be imported.
- rename() method takes two arguments current file nane and new
file name.
- Syntax:
os.rename(current_file_name,new_file_name);
- Example:
#for renaming the file
import os;
=================
Deleting a file
=================
- We can use remove() method to delete files.
- TO remove file, os module need to be imported.
- This method used in python to remove the existing file with the file
name.
- Syntax:
os.remove(file_name);
- Example:
#for deleting files
import os;
print("***Contents of present working directory****");
print(os.listdir());
os.remove("sample123.txt");
print("***Contents of present working directory after remove****");
print(os.listdir());
==============
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 colletion of files and sub-directories.
- Python has the os module which provides us with many useful
methods to wortk with directories.
5) Removing directory:
- The rmdir() method is used to remove directories in the current
directory.
- Syntax:
os.rmdir("dirname");
- Example:
#display lis of files and directories.
import os;
print("***List of files and directories****");
print(os.listdir());
os.rmdir("testdir123");
print("***List of files and directories after remove****");
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-6 File I/O Handling and Exception Handling
print(os.listdir());
=====================
Exception Handling
=====================
- Exception may or may not be occur in our program.
- But when exception is occurred then normal flow of execution of
program got ended.
- When exception is occurred then system generated error messages
got displayed and program execution got ended abnormally.
- Exception is runtime error which may cause due to uncertain
conditions.
- For example, if we divide any value using 0 then divide by zero
exception will occurred.
- By handling exception, we can display meaningful message instead
of system generated error message.
- By handling exception, it will not break the execution of program.
- Suppose, in our pogram there are 10 lines and exeception present
in line no 5 then line no 6 to 10 will not executed if exeception
handling mechanism is not implemented.
- We can handle the exeception using try-except,tey-finally and raise
statemenmts.
- Exception handling mechanism depends on below steps:
1) find the exception
2) throw the exception
3) catch exception
=====================
Multiple except block
=====================
- One try can have multiple except block.
- Suppose exception is occurred then corrsponding exception block
got executed.
-Syntax:
try:
//statements which may cause an exception
except Exception1:
//handle the exception
except Exception2:
//handle the exception
except Exception3:
//handle the exception
else:
//if there is no exception then execute this block.
- Example:
#Exception handling
m=10;
n=0;
try:
c=m/n;
print("Divide=",c);
except ZeroDivisionError:
print("Divide by zero exception is occurred!!!");
except IOError:
print("IOError exception is occurred!!!");
except IndexError:
print("IndexError exception is occurred!!!");
else:
print("Program execution ended successfully!!!");
=======================
try...finally
=======================
- The try statement in python can have an option finally block.
- This block is executed always and is generally used to release
external resources.
- The statements written in finally block is always executed by the
interpreter.
- A finally block is always executed before leaving the try statement.
- Syntax:
try:
//statements which may cause an exception
finally:
//this would always be executed.
- Example:
#try..finally block
m=10;
n=5;
try:
c=m/n;
print("Divide=",c);
finally:
print("I am always executed!!!");
==================
raise statement
==================
- We can use raise keyword for throwing existing exceptions.
- We can write raise keyword and exception name.
- We can explictly throw an exception by using raise keyword.
- Syntax:
raise ExceptionName;
- Example:
#raise statement
age=int(input("Enter Your Age:"));
try:
if(age<18):
raise IOError
else:
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-6 File I/O Handling and Exception Handling
========================
User defined Exception
========================
- As we know that we have different predefined exceptions and that
will occurred when it goes wrong.
- But sometime, we need to creare custom exception that is known
as user defined exception.
- Python allow programmer to create their own exception.
- We can create our own exception by extending predefined class
Exception.
- Programmer can also create and raise own exception.
- Example:
#user defined exception
class InvalidAgeException(Exception):
pass;
age=int(input("Enter Your Age:"));
if age>=18:
print("Eligible for voting!!!");
else:
raise InvalidAgeException;
VJTech Academy…