CBSE Class 12 Computer Science Question 86 of 136

Data File Handling — Question 25

Back to all questions
25
Question

Question 25

What is the difference between the following sets of statements (a) and (b):

(a)

P = open("practice.txt", "r")  
P.read(10)

(b)

with open("practice.txt", "r") as P:  
    x = P.read()
Answer

The code given in (a) will open file "practice.txt" in read mode and will read 10 bytes from it. Also, it will not close the file explicitly. On the other hand, the code given in (b) will open file "practice.txt" in read mode and will read the entire content of the file. Furthermore, it will automatically close the file after executing the code due to the with clause.