Skip to main contentSkip to solution

Identify the correct code to open a file "file1.txt", but not required to close the file using close() statement:

Solution

✅ Correct Option: 4

The with statement is a context manager. It closes the file automatically when its block ends, even if an error occurs, so no close() is needed. The as f part gives the file object a name, so the code inside the block can read from it using f.


Option 2: open("file1.txt") opens the file but returns an object that is not stored or closed, so the file must be closed manually.

Option 3: with without as f gives no name to the file object, so the file cannot be used inside the block.

Option 1: open() is a built-in function, not a method of an object named file, so file.open(...) is wrong.

Keyboard Shortcuts

  • Left arrow: Previous question
  • Right arrow: Next question
  • S key: Jump to solution
  • Q key: Jump to question