Skip to main contentSkip to solution

Arrange the following statement in order to add the content to a text file.

(A) Write the file content using write() method

(B) Open the file in append mode

(C) Take the input from the user

(D) Close the file

Solution

✅ Correct Option: 1

The file must be opened first, then the content collected, written and finally the file closed. Closing is always last because it saves the data and releases the file.

(B) Open the file in append mode, e.g. f = open("a.txt", "a"), so new text is added at the end without erasing existing content

(C) Take the input from the user, e.g. s = input()

(A) Write the content using f.write(s)

(D) Close the file using f.close()


Options 2 and 3: the content is written before it has been taken as input, so there is nothing to write.

Option 4: the file is closed before the content is written, and write() on a closed file raises an error.

Keyboard Shortcuts

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