0% found this document useful (0 votes)
14 views30 pages

Unit 6

The document covers Python's file I/O and exception handling, detailing how to read and write files, open files in various modes, and manage directories. It also explains exception handling using try-except blocks, including the standard exceptions available in Python. Key functions and syntax for file operations and error management are provided with examples.

Uploaded by

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

Unit 6

The document covers Python's file I/O and exception handling, detailing how to read and write files, open files in various modes, and manage directories. It also explains exception handling using try-except blocks, including the standard exceptions available in Python. Key functions and syntax for file operations and error management are provided with examples.

Uploaded by

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

Python

File I/O Handling and


Exception Handling
I/O Operations
• The input/output operations are performed to prepare a
general purpose universal programs that takes input from the
user to process on it and then display result.
• Python performs input-output operations in form of string.
• The output generated is always dependent on the input
values that have been provided to the program.
• The input can be provided to the program statically and
dynamically.
Reading Input
• Python provides two built-in functions to read a line of text
from standard input, which by default comes from the
keyboard.
1)input(prompt):-The input(prompt) function allows user
input. It takes one argument.
Syntax:-input(prompt)
where, prompt is a string, representing a default message
before the input.
Ex:-
x=input(‘Enter your name:’)
print(‘Hello’, +x)
Reading Input
2)input():-The function input() always evaluate the input provided
by user and return same type data.
Syntax:-x=input()
The input value is integer type then its return integer value.
The input value is string type then its return string value.
Ex:-
x=int(input())
print(x)
print(type(x))
o/p:-5
<class ‘int’>
Printing to screen
The function print() is used to output data to the standard
output can redirect or store on to a file also.
The message can be a string, or any other object will be
converted into a string before written to screen.
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.
 sep=‘separator’:-Optional. Specify how to separate the
objets,if there is more than one. Default is ’ ’.
Printing to screen
 end=‘end’:-Optional. Specify what to print at the end. Default
is’\n’.
 file:-Optional. An object with a write method. Default is
sys.stdout.
 Flush:-Optional. A boolean,specifying if the output is
flushed(true) or buffered(false).Default is false.
Ex:-
print(“Hello", "How are you?”,sep=“---”)
File Handling
• File is a named location on disk to store related information. It
is used to permanently store data in non-volatile memory
(e.g.harddisk).
• The use of file handling is important because we know that
every data that we have in our program are actually in
temporary memory block; which gets released as the program
execution ends.
• Now if we want to pursue these values/data/information for
permanent bases then we save them in plain text file and
retrieve it back whenever required.
In python a file operation takes place in the following order:-
• Open file.
• Read or write(perform operation).
• Close the file.
Opening file in different modes
• In python programming while opening a file, file object is
created, and by using this file object we can perform different
set as operations on the opened file.
• Python has a built-in function open() to open a file.
Syntax:-
File object=open(file_name[,access_mode][,buffering])
Parameters:-
• file_name:-This argument is a string value that contains the
name of the file that we want to access.
• access_mode:-The mode in which the file has to be
opened,i.e.,read,write,append,etc.This is a optional prameter
and the default file access mode is read(r).
Opening file in different modes

• r(read):-
Read mode is used when the file is only being read. Places the file
pointer at the beginning of file.

• w(write):-
Write mode which is used to edit and write new information to file.
Truncates and overwrites the file, if the file exists and creates new file,
if the file does not exist.

• a(append):-
Appending mode, which is used to add new data to the end of the file.
New information is automatically adjusted to the end.
• Opening file in different modes
• r : Opens a file for reading only. The file pointer is placed at the beginning of
the file. This is the default mode.

• w : Opens a file for writing only. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

• a : Opens a file for appending. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates
a new file for writing.

• r+ : Opens a file for both reading and writing. The file pointer placed at the
beginning of the file.

• w+ : Opens a file for both writing and reading. Overwrites the existing file if the
file exists. If the file does not exist, creates a new file for reading and writing.
• a+ : Opens a file for both appending and reading. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not
exist, it creates a new file for reading and writing.
• Opening file in different modes

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

• wb : Opens a file for writing only in binary format. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.

• ab : Opens a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.

• rb+ : Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.

• wb+ : Opens a file for both writing and reading in binary format. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for reading and writing.

• ab+ : Opens a file for both appending and reading in binary format. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.
• buffering:-If the buffering value is set to 0,no buffering takes palce.If the
buffering value is 1,line buffering is performed while accessing file.
• If we specify the buffering value as an integer greater than 1,then buffering
action is performed with the indicated buffer size. If negative, the buffer
size is the system default(default behavior).
Built-in function and attributes:-
• read():-To read and return complete contents of file.
• mode:-This attribute contains mode of file in which it is opened.
• name:-This attribute contains name of file.
• closed:-Contains whether file is closed or not.
• close():-Close file and releases file pointer from it.

Ex:-
f=open(“sample.txt”,”r”)
print(“file is opened”)
print(“contents of file:\n”,f.read())
f.close()
print(“file is closed.”,f.closed)
print(“File name is:”,f.name)
print(“File opened in”,f.mode,”mode”)
Reading and writing file
• The write method writes any string into a file.
• Syntax:-
file_obj.write(string_data)
Write() method does not add a newline character(“\n”) to end of the string.
• Ex:-
f=open(“sample.txt”,”w”)
f.write(“This is a file-1.\n”)
f.write(“This is a file-2.\n”)
f.close()
print(“data saved”)
• Writelines():- This function writes a sequence of string to the file.
Ex:- f=open(“sample.txt”,”w”)
list1=[“this is line-1”,”this is line-2”,”this is line-3”,”this is line-4”]
f.writelines(list1)
f.close()
Reading and writing file

• The read() function reads from opened file and returns as string.
Read() function has a parameter, which is length/characters to read.
• readline():- this function reads only one line, in which currently file
pointer is pointing.
• Ex:-
f=open(“simple.txt”,”r”)
print(f.read())
position = f.tell()
print ("Current file position : ", position)
f.seek(0)
print(f.read(12))
f.seek(0)
print(f.readline())
f.close()
#it will read content of file upto-end of file
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)


file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print("Output of Read function is ")


print(file1.read())

# seek(n) takes the file handle to the nth


# byte from the beginning.
file1.seek(0)

print ("Output of Readline function is ")


print (file1.readline())

file1.seek(0)

print ("Output of Readline(9) function is ")


print (file1.readline(9))

file1.seek(0)
# readlines function
print ("Output of Readlines function is ")
print(file1.readlines())

file1.close()
Closing a file
• To close a file, we have built-in close function. This function doesn’t have
parameter.
• Ex:-
f=open(“sample.txt”,”r”)
f.close()

Renaming a file
• To rename a file in python, the os module needs to be imported. The
rename() method is used to rename the file.
• Syntax:- os.rename(current_file_name,new_file_name)
• Ex:-

import os
print(“content of pwd”,os.listdir())
os.rename(“sample.txt”,”sample1.txt”)
print(“content of pwd”,os.listdir())
Deleting a file
• The remove() in python programming is used to remove existing file with
file name.
• This method is used to delete files by supplying the name of the file to be
deleted as a argument.
• Syntax:- os.remove(file_name)
• Ex:-

import os
print(“content of pwd”,os.listdir())
os.remove(“sample.txt”)
print(“content of pwd”,os.listdir())
Directories in python
• A directory is a collection of files and sub directories. Python has the os
module, many built-in functions to work with directories.

• Get Current Directory:-


We can get the present working directories using getcwd() method. This
method returns the current working directory in the form of a string.

Syntax:-os.getcwd()
Ex:- import os
print(os.getcwd())

o/p:-C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\
Python Practice’
Directories in python
• List Directories and files:-
All files and sub-directories inside a directory can be known using
listdir() method.This method takes in a path and returns a list of sub
directories and files in that path. If no path is specified, it returns from the
current working directory.
• Ex:-
import os
print(os.listdir())

• 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. Use the both forward(/) and backward(\) to separate path
elements.
Syntax:-os.chdir(“dirname”)
Ex:- import os
print(os.getcwd()) # O/P: ‘d:\\IT’
os.chdir(“d:\IT\SYCO”)
Directories in python
• Create new directory:-
We can make a new directory using the mkdir() method.
This method takes in the path of the new directory.If the full path is not
specified, the new directory is created in the current working directory.
• Syntax:- os.mkdir(“new directory”)
Ex:- import os
os.mkdir(“dir1”)

• Rename a directories:-
To rename a file or directory of file we have rename()function.
Syntax:- os.rename(“current directory/file”,”new directory/file”)
• Ex:- import os
print(“Initial it has”)
print(os.listdir())
os.rename(“MyOld”,”MyNew”)
print(“after rename it has”)
print(os.listdir())
Directories in python

• Removing a directory:-
The remove() function is to delete file or directory,by specifing its name as
the argument.
Syntax:- os.remove(file_name)
Ex:- import os
print(os.listdir())
os.remove(“dir2”)
print(“after removing”)
print(os.listdir())
Exception Handling
• When we execute a python program ,there may be uncertain
conditions may occur, known as errors.
• An exception is an event which occurs during execution of the
program that disrupts the normal flow of the execution of the
program.
• In python programming we can handle exception using try-except
statement, try-finally statement and raise statement.
• Ex:-
1)print(“15/0 is”,15/0)
o/p:-ZeroDivisionError:division by zero
2)a=[10,20,30]
print(“Second element:”,a[1])
print(“forth element:”,a[3])
o/p:- Index Error:-list index out of range
Exception Handling

• Standard exception available in python:-


1. Exception:- Base class of all exceptions.
2. ImportError:-Raised when an import statement fails to
import.
3. IOError:-Raised when an input/output opertion fails.
4. IndexError:-raised when an index is not found in sequence.
5. ZeroDivisionError:-raised when divisionby takes place for
all numeric types.
6. ArithmeticError:-Base class for all errors that occur for
numeric calculations.
7. SyntaxError:-Raised when there is an error in python syntax.
8. NameError:-Raised when an identifier is not found in local
or global namespaces.
Exception Handling
• try-except block:-try block is a set of statement that may
causes an error during runtime are to be written in try block.
Except block are used to handle any resulting exceptions thrown
in try block. If any statement try block throws an exception ,
control immediately shift to the except block. If no exception is
thrown in try block, the except block is skipped. Multiple except
blocks with different exception names can be chained together.
• Syntax:- try:
certain operations here
except Exception1:
if there is Exception1 ,then execute this block.
except Exception2:
if there is Exception2 ,then execute this block.
Exception Handling
• Ex:-
n=10
m=0
try:
print(“Division:”,n/m)
print(“value of b=”,b)
except ZeroDivisionError:
print(“Divide by zero error”)
except NameError:
print(“No such variable name”)
o/p:-
Divide by zero error
Exception Handling
• try-finally block:-The statement written in finally clause will always be
executed by the interpreter ,whether the try statement raise an exception or
not. When an exception is occurred in try block and has not been handled
by an except block , it is re-raised after the finally block has been executed.
else block is executed when there in no exception or to write any statement.
Else block does not need the try block protection.
• Syntax:-.
try:
certain operations here.
except Exception_name:
if there is Exception_name ,then execute this block.
finally:
this would always be executed.
Exception Handling
• Ex:-
x=int(input(“Enter first value:”))
y=int(input(“Enter second value:”))
try:
result=x/y
except ZeroDivisionError:
print((“Divide by zero error”)
else:
print(“Result is:”,result)
finally:
print(“Execute finally block”)
o/p:-Enter first value:5
Enter second value:0
Divide by zero error
Execute finally block
Exception Handling
• 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.
• Ex:-
try:
age=int(input(“Enter your age for election:”))
if age<18:
raise Exception
else:
print(“you are eligible for election”)
except Exception:
print(“This value is too small, try again”)
o/p:- Enter your age for election:11
This value is too small, try again
Enter your age for election:18
you are eligible for election
Exception Handling
• User defined exception:- Python has many built-in exception which forces our
program to raise an error when something, goes wrong. However ,sometimes we
may need to create custom exception that serve for our purpose. In python we can
define such exceptions by creating a new user defined class that has to either
directly or indirectly be derived from class Exception.
• Ex:-
class MyError(Exception):
pass
print(“Enter any number to multiply with 10:”)
num=int(input())
try:
if num<5:
raise MyError
mult=10*num
print(“Multiplication is:”,mult)
except MyError:
print(“MyError exception is occurred”)
o/p:- Enter any number to multiply with 10:4
MyError exception is occurred

You might also like