Professional Documents
Culture Documents
Unit: V
Course Bloom’s
Outcome At the end of course , the student will be able to: Knowledge
( CO) Level (KL)
CO1 Analyse and implement simple python programs. K3, K4
Relative path
• Relative path is defined as the path related to the current working
directly(cwd). It starts at your current directory and never starts
with a / .
mode Description
“r” Read - Default value. Opens a file for reading, error if the
file does not exist
“w” Write - Opens a file for writing, creates the file if it does not
exist
“a” Append - Opens a file for appending, creates the specified
file if it does not exist
“x” Create - Creates the specified file, returns an error if the file
exists
mode Description
M_tutor Link
https://www.m-tutor.com/courses-detail.php?
tid=859175&topicid=198410&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Handling%20Files%20in%20Python
Example
Loop through the file line by line:
Myfile.txt
f = open(“Myfile.txt", "r")
Hello! Welcome to
for x in f:
Myfile.txt
print(x) This file is for testing
purposes.
Good Luck!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Output:
Woops! I have deleted the content!
Note: the "w" method will overwrite the entire file.
04/01/23 Santosh Kumar Problem Solving using Python Unit V 32
Write to an Existing File (CO5)
write() method is used to write a string to an already opened file.
Strings may include numbers, special characters or other symbols.
write() method does not add a newline(‘\n’) character to the end of
string.
Syntax:
file.write(string)
Output:
Data written to file
M_tutor Link:
https://www.m-tutor.com/courses-detail.php?
tid=859099&topicid=198342&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Reading%20and%20Writing%20Files
• Renaming
• rename() method takes two arguments: Current filename and
new filename
• Syntax:
• os.rename(old_filename,new_filename)
M_tutor Link:
https://www.m-tutor.com/courses-detail.php?
tid=859207&topicid=198444&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Additional%20File%20Methods
import os
os.rename(“file1.txt”, “sudent.txt”)
Print(“File renamed”)
Output:
File renamed
import os
os.remove (“file1.txt”)
print(“File deleted”)
Output:
File deleted
5.makedirs() method:
Used to create more than one directory.
example:
import os
os.makedirs(“C:\\Python12\\dir1\dir2\dir3”)
M_tutor Link:
https://www.m-tutor.com/courses-detail.php?
tid=859190&topicid=198427&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Working%20with%20Directories
1. Write one similarity and one difference between a+ and w+. CO5
2. What is the difference between read() and read(n) functions? CO5
3. What is the difference between readline() and readlines() ? CO5
4. Write a program to read first 10 characters from a file named “data.txt”.
CO5
5. Write a program to read entire content from the file named “test.txt”.
CO5
• What are different file opening modes? [NIET Autonomous 2020-2021(odd), 1 marks]
• Discuss File handling in python. How to perform open, read, write, and close
operations into a text file. Discus CSV files.
[NIET Autonomous 2020-2021(odd), 6 marks]
• Discuss File I/O in python. How to perform open, read, write, and close into a file?
Write a Python program to read a file line-by-line store it into a variable.
[AKTU 2019-2020(odd), 10 marks]
• Write a program to print the name of all the items in the current working directory.
[NIET Autonomous 2021-2022(odd), 2 marks]
• A file named DATA.txt contains a series of integer numbers separated by space. Write
a program to read these number and then write all “odd” numbers to a file called
ODD.txt and all the “even” numbers to a file called EVEN.txt.
[NIET Autonomous 2021-2022(odd), 10 marks]
04/01/23 Santosh Kumar Problem Solving using Python Unit V 70
Expected Questions for University Exam
Exception Handling
• print(x)
• NameError: name 'x' is not defined
• x=5+'c‘
• TypeError: unsupported operand type(s) for +: 'int' and 'str'
• x,y=2,3
• if x==0:
• print(x)
• else:
• print(y)
• IndentationError: expected an indented block
• a= 5/0
– ZeroDivisionError: division by zero
• import ab
– ModuleNotFoundError: No module named 'ab'
• l=[1,2,3]
• l[3]=4
– IndexError: list assignment index out of range
M_tutor Link:
https://www.m-tutor.com/courses-detail.php?
tid=859064&topicid=198307&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Errors%20vs%20Exception
• Assertions
try:
statements
except ExceptionName:
statements
• Python allows you to have multiple except blocks for a single try block.
• The block which matches with the exception generated will get
executed.
• A try block can be associated with more than one except block to
specify handlers for different exceptions.
• Exception handlers only handle exceptions that occur in the
corresponding try block.
• The syntax for specifying multiple except blocks for a single try block can
be given as,
try:
operations are done in this block
………………………………………….
except Exception1:
If there is Exception1, then execute this block,
except Exception2:
If there is Exception2, then execute this block
……………………………………………
else:
If there is no exception then execute this block.
Output:
Enter the number : abc
Please check before you enter ….. Program Terminating ….
Bye
04/01/23 Santosh Kumar Problem Solving using Python Unit V 95
Multiple Exception (CO5)
try:
num = int(input(“Enter the number : ”))
print(num**2)
except(KeyboardInterrupt, ValueError, TypeError):
print(“Please check before you enter….Pogram terminating….”)
Print(“Bye”)
Output:
Enter the number : abc
Please check before you enter….Pogram terminating….
Bye
try:
file = pen(‘File1.txt’)
str=f.readline()
print(str)
except IOError:
print(“Error occurred during Input ………Program Terminating…..”)
except valueError:
print(“Could not convert data to an integer.”)
except:
print(“Unexcepted error……Program Terminating…..”)
Output:
Unexcepted error……Program terminating….
04/01/23 Santosh Kumar Problem Solving using Python Unit V 97
else Clause (CO5)
• The try ... except block can optionally have an else clause, which,
when present, must follow all except blocks. The statement(s) in
the else block is executed only if the try clause does not raise an
exception.
try:
file = open(‘file.txt’)
str = file.readline()
print(str)
Except IOError:
print(“Error occurred during Input…….Program Terminating……”)
else:
print(“Program Terminating Successfully……”)
Output:
Hello
Program Terminating Successfully….
ZeroDivisionError Raised when division or modulo by zero takes place for all
numeric types.
AssertionError Raised in case of failure of the Assert statement.
M_tutor Link:
https://www.m-tutor.com/courses-detail.php?
tid=859130&topicid=198400&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Exception%20Handling
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Output-
Something went wrong
The 'try except' is finished
Output-
Syntax-
assert condition, error_message(optional)
scores1 = []
print("The Average of scores1:",avg(scores1))
Output:
The Average of scores2: 75.8
AssertionError: The List is empty.
M_tutor Link:
https://www.m-tutor.com/courses-detail.php?
tid=859130&topicid=198400&selectedcourse=&selectedsubject=5715&sel
ectedunit=&searchtopics=Exception%20Handling
Answer: d
2. When is the finally block executed?
a) when there is no exception
b) when there is an exception
c) only if some condition that has been specified is satisfied
d) always
Answer: d
• Write a program to prompt the users to input two numbers and display
their sum. Raise an exception and handle it if a non number value is
given as an input.
[NIET Autonomous 2021-22 (odd ), 6 marks]