Skip to main contentSkip to solution

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

✅ Correct Option: 2

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.

Keyboard Shortcuts

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