On Sun, 9 Mar 2025, RAGINI wrote:
Hi,
What is the difference between the two statements:
1.
file = open("myfile.txt")
contents = file.read()
print(contents)
2.
with open("myfile.txt") as file:
contents = file.read()
print(contents)
The latter is a 'compound' statement!
the 'with' statement allows the execution of
- initialization code
- finalization code
around a block of code
In the example above, when you open() a file you also need to close() the file.
In fact, this is going to be a topic for discussion in the upcoming Python
deep-dive session.
warm regards
Saifi.