Unit Vi - File Io Handling and Exception Handling
Unit Vi - File Io Handling and Exception Handling
print(object(s),sep=separator,end=end,file=file,flush=flush)
🞆Parameter values:
1. Object(s) : It can be any object but will be converted to string
before printed.
2. sep=’seperator’ : Optional. Specify how to separate the
objects, if there are more than one. Default is ‘’.
3. end=’end’: Optional. Specify what to print at the end.
Default is ‘\n’(line feed).
4. file: Optional. An object with a write method, Default is
sys.stdout
5. flush: Optional. A Boolean, specifying if the output is
flushed(True) or buffered(False). Default is False.
🞆Example:
print("hello","how are you?",sep="---")
🞆Output: hello---how are you?
🞆Example :
a=12.3456789
print('Value of x is=%3.2f'%a)
print('Value of x is=%3.4f'%a)
Open a file
Read or write (perform operation)
Close the file
How to open a file?
🞆Python has a built-in function open() to open a file. This function
returns a file object, also called a handle, as it is used to read or
modify the file accordingly.
f=open("D:\python programs\Test.txt",'r')
# opening file in r reading mode
print(f.read())
f=open("Test.txt",'w') # Opening file in w writing mode
🞆Output:
Hello
ACCESSING FILE CONTENTS USING
STANDARD LIBRARY FUNCTIONS:
🞆Once a file is opened and you have one file object, you can
get various information related to that file.
🞆List of all attributes related to file object are- Attribute &
Description:
• file.closed -Returns true if file is closed, false otherwise.
• file.mode -Returns access mode with which file was opened.
• file.name -Returns name of the file.
• file.encoding -Returns encoding of the file.
🞆Example:
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","w)
print("Name of the file: ",fo.name)
print("Closed or not : ",fo.closed)
print("Opening mode : ",fo.mode)
print("File encoding : ",fo.encoding)
🞆Output:
Name of the file: F:\2019-2020\PYTH prog\README.txt
Closed or not : False
Opening mode : w
File encoding : cp1252
READING DATA FROM FILES:
read() Method-
🞆The read() method reads a string from an open file. It is
important to note that Python strings can have binary data.
apart from text data.
🞆Syntax :
fileObject.read([count])
🞆Output:
Read String is : Hello
Wo
rld
readline() Method-
🞆Python readline() method will return a line from the file when called.
🞆 The readline() method output the entire line whereas readline(n)
outputs at most n bytes of a single line of a file.
🞆 Once the end of line is reached, we get empty string on further
reading.
🞆 Syntax : fileObject.readline([count])
Here, passed parameter is the number of bytes of a single line to be
read from the opened file.
🞆 Example
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","r")
print(fo.readline())
print(fo.readline(3))
print(fo.readline())
print(fo.readline())
print(fo.readline())
🞆readlines() Method-
readlines() method will return all the lines in a file in the format of a list
where each element is a line in the file.
Syntax : fileObject.readlines()
Example:
fo = open("F:\\2019-2020\\PYTH prog\\README.txt","r")
print(fo.readlines())
WRITING FILES:
🞆There are two ways to write in a file. write(string) :
Inserts the string str1 in a single line in the text file.
Syntax: File_object.write(str1)
Output: str1
str2
str3
CLOSING A FILE:
🞆When we are done with operations to the file we need to
properly close the file.
🞆Closing a file will free up the resources that were tied
with the filed and is done using python close() method.
os.rename(current_filename, new_filename)
🞆# Program for renaming files
import os
print("Present working directory\n",os.listdir())
os.rename("README.txt","newREADME.txt") print("Present
working directory\n",os.listdir())
DELETING A FILE:
🞆We can use the remove() method to delete files by supplying
the name of the file to be deleted as the argument.
🞆To remove a file, the OS module need to be imported.
🞆Syntax: os.remove(filename)
🞆# Program for removing files
import os
print("Present working directory\n",os.listdir())
os.remove(“myfile.txt")
print("Present working directory\n",os.listdir())
WRITE PYTHON PROGRAM TO READ
CONTENTS OF ABC.TXT AND WRITE SAME
CONTENT TO PQR.TXT.
n=10
m=0
try:
n/m
except ZeroDivisionError:
print("Divide by zero error")
else:
print(n/m)
Output:
Divide by zero error
else Clause:
🞆In python, you can also use the else clause on the try-except
block which must be present after all the except clauses.
🞆The code enters the else block only if the try clause does not
raise an exception.
🞆Syntax:
try:
# Some Code
except:
# Executed if error in the try block
else:
# execute if no exception
Finally Keyword in Python
🞆 Python provides a keyword finally, which is always executed after
the try and except blocks.
🞆 The final block always executes after normal termination of try
block or after try block terminates due to some exceptions.
🞆 Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
🞆# Program to check for ZeroDivisionError Exception