Question:

Arrange the following statements in the correct sequence in order to write multiple strings to a file:
(A) myobj.close()
(B) lines= ["Hello everyone $\backslash$n", "writing multiple strings into file"]
(C) myobj.writelines(lines)
(D) myobj = open ("myfile.txt", 'w')
Choose the correct answer from the options given below:

Show Hint

Standard File Life-Cycle in Python:
open() $\rightarrow$ prepare data $\rightarrow$ write() writelines() $\rightarrow$ close().
Never invoke writelines() before creating the file handle via open().
Updated On: Sep 7, 2026
  • (D), (B), (C), (A)
  • (C), (D), (B), (A)
  • (B), (A), (D), (C)
  • (C), (B), (D), (A)
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

Concept:
File input/output handling in Python follows a strict life cycle:
1. Open the file to create a file handle object with the desired access mode.
2. Prepare or initialize the data sequence (strings/lists).
3. Perform the reading or writing operation using file object methods.
4. Close the file object to release operating system resources and flush write buffers.

Step 1: Step-by-Step Program Flow:

- Step 1 (D): myobj = open("myfile.txt", 'w') opens the target file in write mode, returning a valid file handle referenced by variable myobj.
- Step 2 (B): lines = ["Hello everyone $\backslash$n", "writing multiple strings into file"] initializes a list of string elements to be written.
- Step 3 (C): myobj.writelines(lines) takes the list of strings and writes each string element into the open file referenced by myobj.
- Step 4 (A): myobj.close() properly closes the file stream and saves all written content to the disk.

Step 2: Conclusion:

Attempting to write before opening or after closing triggers errors. Therefore, the logical sequence is (D), (B), (C), (A).
Final Answer:
The correct order is (D), (B), (C), (A), which corresponds to option (A).
Was this answer helpful?
0
0

Top CUET File Handling in Python Questions

View More Questions