Skip to main contentSkip to solution

Arrange the following statements in the correct sequence in order to write multiple strings to a file.

(A) myobj.close()

(B) lines= ["Hello everyone \n", "writing multiple strings into file"]

(C) myobj.writelines(lines)

(D) myobj = open ("myfile.txt", 'w')

Solution

✅ Correct Option: 1

The file must be opened first, then the data prepared, then written, and finally closed.

(D) myobj = open("myfile.txt", 'w')

(B) lines = ["Hello everyone \n", "writing multiple strings into file"]

(C) myobj.writelines(lines)

(A) myobj.close()


Option 2 and Option 4: they call writelines() before the file object myobj exists, which gives a NameError.

Option 3: it closes the file before opening it, so the write would fail.

Note that writelines() does not add newline characters itself, so the "\n" must be included in the strings.

Keyboard Shortcuts

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