Arrange the following lines of code for writing into a file in the correct order:
(A) lines = ["Hello Everyone\n", "Writing in multiple lines"];
(B) myobj.writelines(lines)
(C) myobj= open("myfile.txt", 'w')
(D) myobj.close()
Arrange the following lines of code for writing into a file in the correct order:
(A) lines = ["Hello Everyone\n", "Writing in multiple lines"];
(B) myobj.writelines(lines)
(C) myobj= open("myfile.txt", 'w')
(D) myobj.close()
Solution
The list of lines is created first (A). The file is then opened in write mode (C), the lines are written with writelines() (B), and the file is closed at the end (D).
(A) lines = ["Hello Everyone\n", "Writing in multiple lines"];
(C) myobj= open("myfile.txt", 'w')
(B) myobj.writelines(lines)
(D) myobj.close()
Options 1 and 3: (B) calls writelines() on myobj before (C) has opened the file, so myobj does not exist yet.
Option 4: (D) closes the file before the lines are defined and written, and (A) comes last, so nothing useful is written.
writelines() does not add newline characters on its own, so each line needs its own \n.
Related questions:
2026: 23 May Shift 1
2026: 20 May Shift 1
2025: 27 May Shift 2