Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
141 views

Python Notes

The document discusses file handling in Python. It describes how to open, read, write, close, rename and delete files. It also discusses different file modes for opening files, reading and writing file contents using methods like read(), readline(), writelines(), and changing the file position with seek() and tell(). The document also introduces directories and methods for creating, removing directories in Python.

Uploaded by

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

Python Notes

The document discusses file handling in Python. It describes how to open, read, write, close, rename and delete files. It also discusses different file modes for opening files, reading and writing file contents using methods like read(), readline(), writelines(), and changing the file position with seek() and tell(). The document also introduces directories and methods for creating, removing directories in Python.

Uploaded by

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

UNIT-6 File I/O Handling and Exception Handling

================================================
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

III) Close the file.

✓ Opening file in different Modes:


- All files in python are required to be open before some operation.
- While opening file, file object got created and by using that file
object we will perform different operations.
- Python has built-in function open() to open a file.
- Syntax:
fileObject=open(FileName[,AccessMode,buffering]);
- Where:
FileName : Name of the file wthat you want to access.
AccessMode: The access mode determines the mode in which
the file has to be opened i.e read,write, append, etc.
buffering: If the buffering value set to 0 then no buffering takes
place. If the buffering value is 1 then buffering is performed while
accessing file.
- Example:
file=open("vjtech.txt");

✓ Different Modes of Opening File:


1) r : Opens file for reading mode.
2) r+ : Opens file for both reading and writing.
3) w : Opens file for writing only.
4) w+ : Opens file for both reading and writing.
5) a : Opens file for appending.
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-6 File I/O Handling and Exception Handling

6) a+ : Opens file for both appending and reading.


7) rb : Opens file for reading only in binary format.
8) rb+: Opens file for both reading and writing in binary format.
9) wb : Opens file for writing only in binary format.
10)wb+: Opens file for both reading and writing in binary format.
11)ab : Opens file for appending in binary format.
12)ab+: Opens file for both appending and reading in binary format.

- Example:
file=open("vjtech.txt",'w');
- In above example vjtech.txt file opens in writing mode.

✓ Accessing contents of file using standard library functions:


1) file.closed : return true if file is closed.
2) file.mode : return access mode of file.
3) file.name : return name of the file.
4) file.encoding: return encoding of the file.

✓ 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();

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

==========================
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.

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

- 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.

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

- seek() method is used to move file pointer to the particular


position.
- Example:
#file position
f1=open("vjtech.txt","r");
print("current position of file cursor:",f1.tell());
print(f1.read());
print("current position of file cursor:",f1.tell());
f1.seek(0);
print(f1.read());

=================
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;

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

print("***Contents of present working directory****");


print(os.listdir());
os.rename("sample.txt","sample123.txt");
print("***Contents of present working directory after rename****");
print(os.listdir());

=================
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());

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

==============
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.

1) Create new directory:


- We can make new directory using mkdir() method.
- This method takes in the path of the new directory. If the full path
is not specified then new directory is crated in the current working
directory.
- Syntax:
os.mkdir("newdir");
- Example:
#create new directory
import os;
os.mkdir("testdir123");
print("new directory created successfully!!!");

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

2) Get Current Directory:


- We can get the present working directory using getcwd() method.
- This method return the current working directory in the form of
string.
- Syntax:
os.getcwd();
- Example:
#Get current directory
import os;
print(os.getcwd());

3) Changing the directory:


- We can change the current working directory using chdir() method.
- We can pass new path of directory in this method.
- We can use both forward slash(/) and backward slash(\) to separate
path elements.
- Syntax:
os.chdir("dirname");
- Example:
#changing directory
import os;
print(os.getcwd());
os.chdir("F:\Academic 2022\C Language 2022");
print(os.getcwd());

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

4) List directories and files:


- All files and sub directories inside a directory can be display using
listdir() method.
- This method takes in a path and return a list of sub directories and
files in that path.
- If path is not specified then it will return from the current working
directory.
- Exmaple:
#display lis of files and directories.
import os;
print(os.listdir());

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

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

4) handle the exception


-Syntax:
try:
//statements which may cause an exception
except Exception1:
//handle the exeception
else:
//if there is no exception then execute this block.
- In above syntax else block is optional.
- Example:
#Exception handling
m=10;
n=5;
try:
c=m/n;
print("Divide=",c);
except ZeroDivisionError:
print("Divide by zero exception is occurred!!!");
else:
print("Program execution ended successfully!!!");

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

=====================
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);

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

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:

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

#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

print("You are eligible for voting!!!");


except IOError:
print("Exception occurred:Not eligible for voting!!!");

========================
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;

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)


UNIT-6 File I/O Handling and Exception Handling

Inspiring Your Success

VJTech Academy…

Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)

You might also like