Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
19 views24 pages

Files & Exception Handling

The document provides an overview of file handling in Python, covering file types, operations, modes, and methods for reading, writing, and appending data. It also discusses pickling and unpickling for handling complex data types, along with examples of various file operations such as renaming and deleting files and directories. Additionally, it includes code snippets demonstrating how to perform these operations effectively.

Uploaded by

muhammedfuaadc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

Files & Exception Handling

The document provides an overview of file handling in Python, covering file types, operations, modes, and methods for reading, writing, and appending data. It also discusses pickling and unpickling for handling complex data types, along with examples of various file operations such as renaming and deleting files and directories. Additionally, it includes code snippets demonstrating how to perform these operations effectively.

Uploaded by

muhammedfuaadc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

1 MODULE 4

FILES
➢ File is a collection of data. (text,image audio ,or video)
➢ data is stored permanently in the hard disk or any other secondary storage
devices.
➢ Each file has a file name and extension. Extension indicates type of the file.
➢ Eg: s.txt indicates a text file
im.jpg indicates an image file
Text File
o Stores textual data only .
Binary File
o The data is encoded in binary form(0s and 1s)
o It can be of any type (text,image , audio,video etc)
Directory
• When there are a large number of files, they are often organized into
directories (also called “folders”).
• It is an area of the secondary storage device that stores a group of files
• A directory may contain subdirectories.(Subfolders)

FILE OPERATIONS
• File operations include: read data from file ,write data in to file,append data at
the end of the file
• Before performing any operation on the file , we need to open the file
• When the operation is completed the file must be closed.
Open File.-----------> Perform operation------------->Close file

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


2 MODULE 4

FILE MODES IN PYTHON

Mode Description

• Open a file for read only


'r'
• An error message is displayed if the file doesn’t exist

• Open a file for write only.


'w' • if the file exists Overwrite the contents of the file
• if the file doesn’t exist, Creates a new file with that name

• Open a file for append only


• if the file exists ,New data is added at the end of the file
'a'
• Doesnt’t overwrite the original contents of the file
• if the file doesn’t exist, Creates a new file with that name Text
Mode
'r+' Open a file for read and write

'w+' Open a file for write and read

'a+' Open a file for append and read

‘rb’ Open for read only

‘wb’ Open for write only


Binary
‘ab’ Open for append only Mode
‘rb+’ Open for read write

‘wb+’ Open for read and write)

‘ab+’ Open for append and read

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


3 MODULE 4

Opening a file
• Built in function open() is used.
Syntax: fileobject = open(file name.extension,file mode)
o The file object name is used in read, write or append operations.
o We can give any name to the file object.
o If file mode is not specified default mode is ‘r’
Eg: f=open(“D:\docs\test.txt”,’r’)
OR
f=open(“D:\docs\test.txt”) ------> If the file test.txt exists open it for reading
only.
Returns error if test.txt doesn’t exist.
f=open(“D:\ss.txt”,w) -------------> If the file ss.txt exists open it for write only.
overwrite it’s original contents. If the file ss.txt doesn’t exist create a new file
with name ss.txt and open it for writing only.
Closing a file
• After performing operations file should be closed.
Syntax: file object.close()

f=open(----------------)
-------
------- file operations
-------
f.close()

Writing textual data in to file


• To write data open the file in w, w+ or r+ mode
• Write() method is used to write textual data(strings) in to file.
Syntax: file object.write(string)
Eg: f=open(“data.txt”,”w”)
f.write(“Intro.to Python”)

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


4 MODULE 4

• If data.txt already exists, the string is written to the file by overwriting the
original contnts
• If the file data.txt doesn’t exist create a new file with name data.txt and the
string is written to it.
• It doesn’t add new line at the end of string. data.txt
For eg: f.write(“Intro.to Python”) Intro.to PythonModule1

f.write(“Module 1”)
Here both strings are stored in the same line in the file.
• To store the second string in the next line \n is used data.txt
ie f.write(“Intro.to Python\n”) Intro.to Python
f.write(“Module 1”) Module1

Now 2nd string is stored in the new line.

Appending textual data in to file


• To append data open the file in a, or a+ mode
• Write() method is used to append textual data(strings) in to file.
Syntax: file object.write(string)
Eg: f=open(“data.txt”,”a”)
f.write(“Intro.to Python”)
If data.txt already exists, the string is added at the end of the file. Doesn’t
overwrite original contnts
If the file data.txt doesn’t exist create a new file with name data.txt and the string
is written to it.

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


5 MODULE 4

Reading textual data from file


• To read textual data we have to open the file in r r+ or a+ mode
Syntax:
fileobject.read(no.of characters): Used to read a specified no.of
caharacters. If no.of character is not specified entire contents of the file is read.
Eg: s.txt
Eg:f.read(6) reads & returns first 6 characters
Good morning
ie ‘Good m’
Hello world
f.read() reads & returns the entire contents
ie ‘Good morning’
‘Hello world’

Reading individual lines


• readline() is used to read & return individual lines from the file.
• This function reads the data until a new line is found
Eg: f=open(‘s.txt’,’r’)
f.readline() ----------------> ‘Good morning’
f.readline()-----------------> ‘Hello world’
f.close()
• readlines() is used to read the entire lines from the file and returns the lines as a
list.
f=open(‘s.txt’,’r’)
f.readlines() -------------> [‘Good morning\n’ ,’Hello world’]
Difference between read and readline()
• Both read and read line() is used to read textual data from file.
• read() function is used to read a specified no.of characters or the entire contents
of file.
• readline() is used to read individual lines of the file.

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


6 MODULE 4

Another method to read the textual content of the file line by line
syntax: for var in file object: • where var is the variable name.
• here each line of the file is stored in the
print var
variable and it is displayed.
Eg: contents of s.txt :
Good morning
Hello world

f=open(‘D:\s.txt’,’r’)
for i in f: o/p • Here i represents
print i Good morning each line in the file
Hello world
f.close()

• When we perform operation on the file a file pointer points each character
during operation.
• when a read() function is used the file file pointer goes to last position.
• In order to bring the file pointer to the beginning, seek() function is used.
f.seek(0,0) brings the file pointer to start location.
f.seek(2,0) brings the pointer to the character2 from start(beg. from 0)
f.seek(5,0) brings the pointer to the character5 from start(beg. from 0) etc
s.txt
Good morning

f=open(“D:/s.txt”, ”r”)
f.read()-------> ’Good morning’
f.read()-------> ‘ ‘
f.seek(0,0)
f.read()------->’Good morning’
f.seek(2,0)
f.read()------->’od morning’

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


7 MODULE 4

1. Opens a file for input and display the count of 4 letter words
f=open(“D:/s.txt”,”r”)
n=0 ‘e’ represents each line in the file Contents of s.txt

for e in f: split each line e in to a list of words , x Hello World


x=e.split()
‘i’ represents each word in the list Haii Good Morng
for i in x:
if(len(i)==4): If word length = 4 , n is incremented
n=n+1
print n 1. e:Hello World
f. close() x=[‘Hello’ , ‘World’]
i=Hello i=World

2. e:Haii Good Morng


x=[‘Haii’ , ‘Good’ , ‘Morng’]
i=Haii i=Good i=Morng

2. Read a file and write out a new file with the lines in reversed order
import pickle
f1=open(“D:/s1.txt”,”r”)
f2=open(“D:/s2.txt”,”w”)
for i in f1:
f2.write(i[::-1])
f2.write(“\n”)
f1.close()
f2.close()

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


8 MODULE 4

PICKLING and UNPICKLING(important)


• read() ,readline(),write() methods can only be used to read or write strings in
text files.
• pickling and unpickling are used to handle other data types (list,dictionary,
tuple etc) with files(Binary files)
• These can be used with strings also.
• Pickling is the process of converting pyhon objects (list,tuple ,dictionary etc)
in to a byte stream for storing(writing) them in to a file.
• Unpickling is the reverse process. ie the byte stream is converted back in to
python objects when a file is read.
• Pickling is also known as Serialization or Marshalling or Flattening
• Unpickling is also known as De-serialization,Unmarshalling, Unflattening.
• To use pickling or unpickling feature we have to import a module known as
pickle.
import pickle
• File should be opened in binary mode for using this feature
• The pickle module has two main methods for reading and writing data.
1.dump() 2.load()
1.dump() : Used to write a python object (list,tuple etc) in to a file. ie this
method is used for pickling.
Syntax: pickle.dump(python object,file object)
The python object is written in to the file
2.load() : Used to read a python object (list,tuple etc) from a file. ie this
method is used for unpickling.
Syntax: python object = pickle.load(file object)
The data is read from the file and stored in the python object.

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


9 MODULE 4

PROGRAMS
• If the file name is not specified in the question we can assume any name.

1.write a number in to a file


import pickle

f=open(“D:/data.txt”,”wb” ) open the file in binary write only mode

a=input(“Enter a number”) Read no.from keyboard and store in variable a.Here a


is the python object

pickle.dump(a,f) write the no.stored in a in to file

f.close()

2.Suppose the file data.txt contains an integer number.read the number from file
f=open(“D:/data.txt”,”rb” )
Read no.from file and store it in the variable b.Here b is the python
b=pickle.load(f) object
print”Number is”,b
f.close()

3.Write a group of numbers in to a file


import pickle
l=[]
n=input(“How many nos”)
for i in range(1,n+1,1): Here we create a list of n numbers(l). l is the python
x=input(“Enter a no.”) object .
l.append(x)
f= open(“D:/data.txt”, ”wb” )
pickle.dump(l,f) write the list object in to file .
f.close()

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


10 MODULE 4

4.Read a group of numbers from the file


suppose the file d.txt contains a group of of numbers.

import pickle
f= open(“D:/data.txt”, ”rb” )
l=pickle.load(f) Read numbers from the file in to list l.
f.close()

7. Read numbers stored in one file and store the sorted numbers in another file
after deleting duplicates.
import pickle
f=open(“D:/data1.txt”,”rb”)
l=pickle.load(f) Read numbers from the file in to a list l
f.close()
l.sort()
l2=[]

for i in l: i represents each number in the list


if(i not in l2):
If no.is not in list l2 already , add it to list l2.
l2.append(i)

f=open(“D:/data2.txt”,”wb”)
pickle.dump(l2,f) Write list l2 to data2.txt
f.close()

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


11 MODULE 4

8. Read numbers from a file num.txt. Write all the +ve numbers from num.txt to
positive.txt and negative numbers to negative.txt
import pickle
f=open(“D:/num.txt”, ”rb”)
l=pickle.load(f) Read numbers from the file in to a list l
f.close()

for i in l: i represents each number in the list

if(i>0):
l1.append(i)
If no.is positive , add it to list l1.If negative add to list l2
else:
l2.append(i)

f1=open(“D:\positive.txt”, ”wb”)
pickle.dump(l1,f) Write list l1 to positive.txt

f1.close()

f2=open(“D:/negative.txt”,”wb”)
pickle.dump(l2,f) Write list l2 to negative.txt
f2.close()

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


12 MODULE 4

RENAMING FILES
• rename() function is used to rename a file.
• It is defined in the os module
Syntax: os.rename(oldname,new name)
Eg: import os
os.rename(“D:/s.txt”, “D:/s1.txt”)

DELETING FILES
• remove() function is used to delete a file.
• It is defined in the os module
Syntax: os.rename(filename)
Eg: import os
os.remove(“D:/s.txt”) → s.txt will be deleted

DIRECTORY OPERATIONS
• Methods are defined in the os module

CREATING A DIRECTORY
• mkdir() function is used to create a new directory
Syntax: os.mk dir(directoryname)

REMOVING A DIRECTORY
• rmdir() function is used to delete a directory
• Before removing a directory , all the contents of that directory should be
removed
Syntax: os.rmdir(directory name)

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


13 MODULE 4

RENAMING A DIRECTORY
• rename() function is used
Syntax: os.rename(old name , new name)
Eg: import os
os.rename(“D:/Files”, “D:/PythonFiles”)

CHANGE DIRECTORY
• chdir() function is used to change from current working directory to another
directory
Syntax: os.chdir(directory name)

GET CURRENT WORKING DIRECTORY


• getcwd() function is used to get the current working directory
Syntax: os.getcwd()

LISTING THE FILES AND SUBDIRESORIES INSIDE A DIRECTORY


• listdir() function is used
Syntax: os.listdir(directory name)

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


14
MODULE 4

EXCEPTIONS
TYPES OF ERRORS
Syntax error
• Error caused by the violation of syntax rules of the language.

Eg:
if(a>b) a=…
print a b=….
if(a>b):
Correct statement according .to syntax is: print “b is greater”
if(a>b):
else:
print a
print “a is greater”
Logical Errors
• Errors occur due to incorrect logic.
• Programs may run without halt, but it gives incorrect result.
Eg:
s=a-b
print(“sum=”,s)

Runtime Error
• Error that occurs during the execution of the program. These errors are
called Exceptions.
Eg: If we input the value 0 for ‘b’ c=a/b
a=input(“Enter a number”) can’t be executed .As a result the
b=input(“Enter second number”) program halts.
c=a/b
print c

EXAMPLES FOR EXCEPTIONS

1.ZeroDivisionError: If the second operand of division is zero.

a=input()
b=input()
c=a/b
If we enter 0 for b , ZeroDivisionError is displayed

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


15
MODULE 4

2.ValueError: when a function receives invalid values or the operand values of


an operator are invalid.
Eg: import math
math.sqrt(-10)

3.TypeError: when a function or operator is using values of incorrect type

Eg: s= "Hello"
The + (addition) operator cannot be used
n= 4
between these two types
x=s+n

4.IndexError: when the index of a sequence(string,list,tuple etc) is out of range


Eg: x=[5,10,20] Here index values are from 0 to 2. So IndexError
print x[4] will be displayed

6.FileNotFound: If we try to open a file that doesn’t exist in read mode .


Eg: f=open("D:\ss.txt","r")
If the file ss.txt doesn’t exist FileNotFound error will be displayed

7.Import Error: when the imported module is not available or found.


import maths There is no module named maths in Python.So import
maths.sqrt(1000) error will be displayed

HANDLING EXCEPTIONS
Using try/except statement
• The group of statements that may cause an exception is placed inside
the try block and the code that handles exception is written in one or
more except blocks
Syntax:
try:
statements that may cause exception
except exception1:
statements to be executed if exception 1 occurs
except exeption2:
statements be executed if exception 2 occurs etc.

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


16
MODULE 4

Working

• First, the statements between the try and except keywords is executed.
• If no exception occurs, the except statements are skipped and execution of
the try statement is finished.
• If an exception occurs during execution of the try statement, the rest of the
statements in the try block is skipped. Then if its type matches with any of the
exception named after the except keywords, that except block is executed..

• A single try statement can have multiple except statements.


Only one will be executed in case an exception occurs.

Eg:
try:
a=input(“Enter a number”)
b=input(“Enter second number”)
c=a/b
print c
except ZeroDivisionError:
Print ”Division by zero-Not possible”
except TypeError:
Print ”Unsupported types for division operation”

• Multiple exceptions can be placed in a single except statement.


try:
a=input(“Enter a number”)
b=input(“Enter second number”)
c=a/b
print c
except (ZeroDivisionError, TypeError):
print ”Division -Not possible”

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


17
MODULE 4

• We can also use a generic except clause, which handles any exception

try:
a=input(“Enter a number”)
b=input(“Enter second number”)
c=a/b
print c
except:
print”Division -Not possible”

RAISING AN EXCEPTION
• In Python programming, exceptions are raised when corresponding errors occur at
run time, but we can forcefully raise it using the keyword raise.

try:
a = int(input("Enter a positive integer: ")
if a <= 0:
raise ValueError
except ValueError :
print “Invalid”

Finally statement (finally block)


• The try statement in Python can have an optional finally statement(block).
• This clause is always executed no matter if the exception is occurred or not

Eg: try:
a=input(“Enter a number”)
b=input(“Enter second number”)
c=a/b
print c
except ZeroDivisionError:
Print ”Division by zero-Not possible”
except TypeError:
Print ”Unsupported types for division operation”
Finally:
Print “Try except block is completed”
DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


1

UNIVERSITY QUESTIONS-THEORY
MODULE 4
2019 scheme

Refer note page 3,8

Refer note page 15

import os.path
f=os.path.exists(filepath)
print (f)

2015 scheme repeated

page 1

Ans) An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program.Exception handling helps maintain the
normal, desired flow of the program even when unexpected events occur

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


2

Explain about exception handling mechanisms in Python -page 15

Refer page,8

open,close,read,write,rename etc Refer Note

Refer page 5,2

open(),close(),write(),readline(), ….. etc explain any 4 . Refer Note

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


3

12. Output : ZeroDivision Error

The denominator of the division operation should be a non zero numeric value.
If the demonimator is zero then ZeroDivisionError will be displayed.
13. ZeroDivisionError,ValueError,TypeError,FileNotFoud Error etc. Refer note

import os.path
f=os.path.exists(filepath)
print (f)

Ans)
The group of statements that may cause an exception is placed inside the try block
and the code that handles exception(statements to be executed if exception occurs )
is written in except blocks
try:
fname=raw_input(“Enter File Name:”)
fhand=open(fname)
except FileNotFoundError:
Print ”File Doesn’t Exist-Please Enter a Valid File Name”

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


4

• After writing the lines the file test.txt will be Apples


Mangoes
Grapes

• here readline() reads and returns the first line. After reading 1st line file pointer goes to the
starting of 2nd line
• readlines() reads from second line onwards . It reads 2 nd and 3rd lines and returns the lines as a
list. \n is also included in the line(except the last line)

Output
Apples
['Mangoes\n', 'Grapes']

Note f=open(‘s.txt’,’r’)
f.readline()
Suppose the contents of the s.txt is:
Output: Good morning
Good morning f=open(‘s.txt’,’r’)
Hello world f.readlines()
Output: [‘Good morning\n’,’Hello world’]
f=open(‘s.txt’,’r’)
f.read()
Output: Good morning
Hello world

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


5

2019 SCHEME PROGRAMS

Ans 17a)
try:
i=1
while(True):
print (i)
if(i==20):
raise StopIteration
i=i+1
except StopIteration :
exit()

Ans 17b) Here ‘i’ represents each line in the


f= open("s.txt" , "r"); file.

for i in f:
if( i.find("Python") != - 1): find function returns the starting index of
the word “python” in a line if the line
print (i)
contains the word “python”

If a line doesn’t contains the word


“python” find() function returns -1

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in


6

Ans 18b)
f1=open("s1.txt", "r")
f2=open("s2.txt", "w") read the entire contents of the file s1.txt in ‘x’

x =f1.read() replace all full stops with commas


y= x. replace( "." ,",")
f2.write(y)
f1.close()
f2.close()

f1=open("s1.txt", "r")
f2=open("s2.txt", "w")
strip() function removes the leading and
for i in f1: trailing blank spaces from a line.
if(i.strip()!=""): The resulting ine after removing the leading
f2.write(i) &trailing spaces is also blank , then the entire
line is a blank line
f1.close()
f2.close()

Refer page 13

DHANYA V,AP IN IT,CEV

Downloaded from Ktunotes.in

You might also like