Computer Science

What is the difference between the following set 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()

Python File Handling

1 Like

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.

Answered By

3 Likes


Related Questions