Identify the correct code to open a file "file1.txt", but not required to close the file using close() statement:
Identify the correct code to open a file "file1.txt", but not required to close the file using close() statement:
Solution
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.
Related questions:
2026: 18 May Shift 2
2025: 22 May Shift 1
2026: 31 May Shift 1