Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

Which of these correctly opens a file for reading and guarantees it is closed?

  1. A f = open('data.txt'); f.read()
  2. B with open('data.txt') as f: f.read()
  3. C file = read('data.txt')
  4. D open('data.txt').close()
Answer

with open('data.txt') as f: f.read()

The with statement closes the file even if an exception occurs inside the block, which manual open and close does not guarantee.

All Python MCQs

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as