-2
with open('/content/test1.txt','r',encoding='utf-8')as f:
f.read()

this does not gives an output

f =open('/content/test1.txt','r',encoding='utf-8')
f.read()

***but this works good ***

krmogi
  • 2,588
  • 1
  • 10
  • 26
  • Both of them work if the indentation is correct. But neither would give an output except in specific cases in the interactive prompt. If you're doing it in an interactive prompt, wrap the `f.read()` calls in `print()` to consistently produce output. Or to store it, assign it somewhere; it's usually pretty useless to read from a file and not store the result anywhere. – ShadowRanger Jan 30 '22 at 18:36
  • It is already answered [here](https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for) for example. – Benjamin Rio Jan 30 '22 at 18:36

1 Answers1

1

with open is using a context manager. It means that within the block that follows, the __enter__ method is called, then at the end of that block the __exit__ method is called. Between those they are equivalent.

If you called read() on f within the block, you'd find the same behavior:

with open('/content/test1.txt', 'r', encoding='utf-8') as f:
    f.read()

The nice part of the file context manager is that the close method is called for you.

theherk
  • 6,954
  • 3
  • 27
  • 52