0% found this document useful (0 votes)
121 views57 pages

Python File Handling and Exceptions

The document discusses working with files in Python. It describes how to open files using the open() function and the different modes that can be used like 'r', 'w', and 'a'. It also covers reading and writing data to files, including reading specific amounts of data or all lines. Exceptions that can occur when working with files are mentioned. Methods for copying, moving, and deleting files and directories are also summarized.

Uploaded by

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

Python File Handling and Exceptions

The document discusses working with files in Python. It describes how to open files using the open() function and the different modes that can be used like 'r', 'w', and 'a'. It also covers reading and writing data to files, including reading specific amounts of data or all lines. Exceptions that can occur when working with files are mentioned. Methods for copying, moving, and deleting files and directories are also summarized.

Uploaded by

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

FILES AND EXCEPTIONS

WORKING OF OPEN()
FUNCTION
We use open () function in Python to open a file in read or write mode.
So, the syntax being: open(filename, mode). There are three kinds of mode, that
Python provides and how files can be opened:
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
“ r+ “, for both reading and writing
The mode argument is not mandatory. If not passed, then Python will assume it to be
“ r ” by default.
FILE MODES IN PYTHON
Mode Description

'r' This is the default mode. It Opens file for reading.


This Mode Opens file for writing.
'w' If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
Open file in append mode.
'a' If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.

'b' This opens in binary mode.

This will open a file for reading and writing (updating)


FILES
 To open a file, you specify its name and indicate whether you want to read or write

>>> f = open("test.txt","w")
>>> print (f)
<open file ’test.txt’, mode ’w’ at fe820>

 First argument: Name of the file


 Second argument: mode (“r” for Read/”w” for Write)

 If there is no file named test.txt, it will be created. If there already is one, it will be
replaced by the file we are writing.
 If we try to open a file that doesn’t exist, we get an error:
>>> f = open("test.cat","r")
IOError: [Errno 2] No such file or directory: ’test.cat’
WRITING DATA
 write() is used to write a string .
writelines() method is used to write a list of strings
To put data in the file we invoke the write method on the file object with w
>>> f = open("test.txt","w")
>>> f.write("Now is the time")
>>> f.write("to close the file")

 Closing the file tells the system that we are done writing and makes the file
available for reading
>>> f.close()
fo = open("D:/pyt.txt", "r")
fo.read()
o/p: 'Hello\nHru\nI AM PYTHON‘
fruits = ["Apple\n", "Orange\n", "Grapes\n", "Watermelon"]
f = open("add.txt", "w")

f.writelines(fruits)
f.close()

f = open(“add.txt", "r") o/p:


Apple
print(f.read()) Orange
Grapes
Watermelon
READING DATA
 To read the data from the file we invoke the read method on the file object with r
>>> f = open("test.txt",“r")
>>> text = f.read()
>>> print (text)
Now is the timeto close the file

 Read can also take an argument that indicates how many characters to read
>>> f = open("test.txt","r")
>>> print (f.read(5))
Now i
READING DATA
there are three ways for reading the data from the file:
read ( ): returns the read bytes in the form of a string. ...
readline ( ): reads a line of the file and returns in the form of a string. ...
readlines ( ): reads all the lines and returns them as a string element in a list.
READING CONTINUED
 If not enough characters are left in the file, read returns the remaining characters.
When we get to the end of the file, read returns the empty string:
>>> print f.read(1000006)
s the timeto close the file
>>> print (f.read())
>>>
APPENDING DATA IN FILE
f = open(“text.txt”,”a”)
f.write(“ this text is for appending “)
f.close
'''

with:
The with statement automatically takes
care of closing the file once
it leaves the with block, even in cases of
error.
# COPY FILE
print("Enter the Name of Source File: ")
source = input() #cse.txt. must be already created with some
contents
print("Enter the Name of New copied File: ")
cfile = input()
f = open(source, "r") #read original file
x = f.readlines()
f.close()
f = open(cfile, "w")
for i in x:
f.write(i) # write already read contents in new file
f.close()
print("\nFile Copied Successfully!")
# Copy one file contents into other %%

f1 = open("CSE.txt", "r")
f2 = open("copyn.txt", "a")
for i in f1:
f2.write(i.upper())
f2.close() #here , must close only then contents
will be written

print("Check, new file is created with full


contents")
TEXT FILES
 A text file with three lines of text separated by newlines
>>> f = open("test.dat","w")
>>> f.write("line one\nline two\nline three\n")
>>> f.close()
 The readline method reads all the characters up to and including the next newline character:
>>> f = open("test.dat","r")
>>> print (f.readline())
line one
>>>
 readlines returns all of the remaining lines as a list of strings:
>>> print (f.readlines())
[’line two\012’, ’line three\012’]
#code of previous slide
f = open("test.dat","w")
f.write("line one\nline two\nline three\n")
f.close()
f = open("test.dat","r")
print (f.readline()) #only 1st line before \n
print (f.readlines())# rest lines as same open() is continued on
test.dat
'''o/p:
line one
['line two\n', 'line three\n']'''
#WRITING VARIABLES IN A
FILE
x=500
f = open("test.dat","w")

f.write(str(x))
f.close()

f = open("test.dat")
print(f.read())
DIRECTORIES
 If you want to open a file somewhere else, you have to specify the path to the file, which is the name
of the directory (or folder) where the file is located:

>>> f = open(“D:/foldername/newfile.txt”,”w”)
>>> f.write(This is the file in new Directory)

 This example opens a file named words that resides in a directory named dict, which resides in share,
which resides in usr, which resides in the top-level directory of the system, called /.
You cannot use / as part of a filename; it is reserved as a delimiter between directory and filenames.
DELETE A FILE
To delete a file, you must import the OS module, and run its os.remove() function

import os
os.remove(“test.txt")
DELETE FOLDER
To delete an entire folder, use the os.rmdir() method

import os
os.rmdir("myfolder")
PICKLING
 As things are written as strings in files.
f = open("test.dat","w")

i.e: f.write ( str([1, 2, 3] ) )


f.write (str(99.6))
Here, problem is: while reading it, we get string.
Original Type information of data is lost.
i.e: f.readline() will results ’ [1, 2, 3]99.6’
Here The solution is pickling.
To get the original data structures back (like lists, dictionaries), use the concept of Pickling. To use it,
import pickle and then open the file in the usual way:

>>> import pickle


>>> f = open("test.pck","wb")

 To store a data structure, use the dump method and then close the file in the usual way:
The dump() method is used when the Python objects have to be stored in a file.
>>> pickle.dump([1,2,3], f)
>>> pickle.dump(99.6, f)
>>> f.close()
PICKLING - CONTINUED
 The load() method of Python pickle module reads the pickled byte stream of one or more
python objects from a file object.
Then we can open the file for reading and load the data structures we dumped:

>>> f = open("test.pck","rb")
>>> y = pickle.load(f)
>>> y
[1, 2, 3]
>>> type(y)
<type ’list’>
>>> x = pickle.load(f)
>>> x
99.6
>>> type(x)
<type ’float’>
MORE EXAMPLES ON PICKLE
import pickle as p
f=open("dump.txt","wb")
p.dump(99.6, f)
p.dump(87, f)
f.close()
f=open("dump.txt","rb")
x=p.load(f)
print(x)
x=p.load(f)
print(x)
 
CODE OF ABOVE SLIDEf=open("dump.txt","rb")
#pickling for serializable call to stored
objects x=p.load(f)
import pickle as p print(x, type(x))
f=open("dump.txt","wb") x=p.load(f)
p.dump(99.6, f) print(x, type(x))
p.dump([22,33,44],f) x=p.load(f)
p.dump(87, f) print(x, type(x))
p.dump({9,8,7,6,5,4},f) x=p.load(f)
p.dump((9,8,7,6,5,4),f) print(x, type(x))
p.dump({1:"Ram",2:"Sham"},f) x=p.load(f)
f.close() print(x, type(x))
x=p.load(f)
print(x, type(x))
EXCEPTIONS
 Whenever a runtime error occurs, it creates an exception. Usually, the program stops and Python prints
an error message.
For example,
>>> print (55/0)
ZeroDivisionError: integer division or modulo

>>> a = []
>>> print (a[5])
IndexError: list index out of range

>>> b = {}
>>> print (b[’what’])
KeyError: what

>>> f = open("Idontexist", "r")


IOError: [Errno 2] No such file or directory: ’Idontexist’
EXCEPTIONS
 The error message has two parts: the type of error before the colon, and specifics
about the error after the colon. Sometimes we want to execute an operation that
could cause an exception, but we don’t want the program to stop. We can handle the
exception using the try and except statements.

 The try statement executes the statements in the first block. If no exceptions occur,
it ignores the except statement. If an exception of type IOError occurs, it executes
the statements in the except branch and then continues.
EXCEPTIONS
 The raise statement takes two arguments: the exception type and specific
information about the error. ValueError is one of the exception types Python
provides for a variety of occasions. Other examples include TypeError, KeyError,
and my favorite, NotImplementedError.
 If the function that called input Number handles the error, then the program can
continue; otherwise, Python prints the error message and exits:
# ValueError is an inbuilt exception to give a message

def number():
x=input("Enter a Value")
if(x=="7777"):
raise ValueError("not good")
else:
print(“I am a Good Value")
number()
Use of try, except, finally
#try except finally:
def divide(x, y):
try:
# Floor Division : Gives only Fractional
result = x // y
print("Your answer is :", result)
except:
Output:
print("Sorry ! You are dividing by zero ")
Your answer is : 1
finally: I always appear
print("I always appear\n")
Sorry ! You are dividing by zero
I always appear
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)
SOME BUILT-IN EXCEPTIONS

ZeroDivisionError Raised when the second operator in a division is zero


ValueError Raised when there is a wrong value in a specified data type
TypeError Raised when two different types are combined
SyntaxError Raised when a syntax error occurs
ArithmeticError Raised when an error occurs in numeric calculations
Exception Base class for all exceptions
IndentationError Raised when indendation is not correct
WRITING VARIABLES
 To write data types other than string, do (Here x is a value)

>>> x = 52
>>> f.write (str(x))
or use the Format Operator /format specifier (%)
>>> cars = 52
>>>"%d" % cars
’52’

Another example:

>>> cars = 52
>>> "In July we sold %d cars.“ % cars
’In July we sold 52 cars.’
WRITING VARIABLES –
FORMAT OPERATOR
 %f for floats, %s for strings, %d for decimal values
>>> "In %d days we made %f million %s." % (34,6.1,’dollars’)
’In 34 days we made 6.100000 million dollars.’
>>> "%d %d %d" % (1,2)
TypeError: not enough arguments for format string
>>> "%d" % ’dollars’
TypeError: illegal argument type for built-in operation
 For more control over the format of numbers, we can specify the number of digits as part of the format
sequence:
>>> "%6d" % 62
’ 62’
>>> "%12f" % 6.1
’ 6.100000’

The number after the percent sign is the minimum number of spaces the number will take up.
WRITING VARIABLES –
FORMAT OPERATOR
 If the value provided takes fewer digits, leading spaces are added. If the
number of spaces is negative, trailing spaces are added:
>>> "%-6d" % 62
’62 ’
 For floating-point numbers, we can also specify the number of digits after
the decimal point:
>>> "%12.2f" % 6.1
’ 6.10’
QUESTIONS
1. Write a program that removes all the occurrences of a specified string from a file. Your
program should prompt the user to enter a filename and a string to be removed.
2. Write a program that will count number of characters, words and lines in a file.
3. Suppose that a text file contains an unspecified number of scores. Write a program that reads
the scores from the file and display their total and average. Scores are separated by blanks. Your
program should prompt the user to enter a filename.
4. Write a program that write 100 random integers. Integers are separated by space in file. Read
the data back fro the file and display the sorted data.
5. Write the program to replace the text in a file. Your program should prompt the user to enter
filename, old string, new string.
6. Write the program that counts the number of characters in a given line
http://cs.Armstrong.edu/liang/Data/Lincoln.txt
#Write a program that removes all the occurrences of a specified string from a file. Your program
should prompt the user to enter a filename and a string to be removed.
f = open("D:/del.txt", "w")
f.write("Delete all H and i when both are together")
f.write("\nHello Hi PythonHiCSE Hi Hello Hi") # delete all Hi
f.close()

f = open("D:/del.txt", "r")
f1=f.read()
d = f1.replace("Hi","") # No more Hi will be in fi file
print(d)
o/p:Delete all H and i when both are together
Hello PythonCSE Hello
randint(1,2000)
import random
randomlist = []
for i in range(0,5):
n = random. randint(1,2000)
randomlist.append(n)
print(randomlist)
#Store n Random Numbers in a file.
import random
def main():
n =int(input("Enter how many nos: " ))
outfile =open("D:\\nos.txt","w")
for i in range(n): # all nos can be between range 1 to n
outfile.write(str(sorted(random.randint(1,500)))+"\t")
outfile.close()
print("NOW READ below what random nos were saved")
f =open("D:\\nos.txt","r")
print(f.read())
main()
print("OR Check in file at given path , you will get data")
SAME
CODE AS
ABOVE
EXAMPLE 1
 The following function copies a file, reading and writing up to fifty characters at a time.
The first argument is the name of the original file; the second is the name of the new file
oldfile=“file.txt”
Newfile=“new.txt”
#COPY one file to another
def cop(old,new):
f1=open("cse.txt", "r")
f2=open("new.txt", "w")
while True:
x=f1.read()
if x=="":
break
f2.write(x)

f1.close()
f2.close()
cop("cse.txt","new.txt")
EXAMPLE 2
 The following is an example of a line-processing program. filterFile makes a copy
of oldFile, omitting any lines that begin with #:
#COPY file cse to new
f=open("cse.txt", "r")
p=open("new.txt", "w")

p.write( f.read() )
COPY
Write the program to replace the text in a file. Your
program should prompt the user to enter filename, old
string, new string.

Hint: Can Use replace function


replace(old string, new string)
Write a program that removes all the
occurrences of a specified string from a file.
Your program should prompt the user to enter a
filename and a string to be removed.
E.g: “Hi Hello Hi Hru Hi I am Fine” in a file.
Delete “Hi” from it
Hint replace (“Hi”, “”)
PROGRAM

To open a file and write in it, then


count total vowels, consonants, upper,
lower
PROGRAM
13 # Implement a stack using list
Hint:
list.append(x)
y=len(list)
for i in range (y,0,-1):
list.pop())
list=[]
n=int(input("How many Values to push"))
for i in range (n):
x=int(input("Enter Value to push"))
list.append(x)
y=len(list)
print("Total elements pushed in list are = ", y)
print("Stack of elements is", list)
 
for i in range (y,0,-1):
print("popped element is:",list.pop())
 
print("Pending elements in Stack are", len(list),"and stack is",list)

You might also like