Q.Run the above code by replacing writelines() with write() and see what happens.
[Context: the code referred to is:
myobject=open("myfile.txt",'w')
lines = ["Hello everyone\n", "Writing #multiline strings\n", "This is the #third line"]
myobject.writelines(lines)
myobject.close()]
myobject=open("myfile.txt",'w')
lines = ["Hello everyone\n", "Writing #multiline strings\n", "This is the #third line"]
myobject.writelines(lines)
myobject.close()]
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The writelines() method writes a list of strings to a file in one call, while write() writes a single string — so replacing writelines() with write() will cause a TypeError because you cannot pass a list to write().
The Core Idea: File Write Methods
When you open a file in write mode ('w'), Python gives you two main tools for putting data into it:
write(string)— writes exactly one string argument. If you need multiple lines, you must call it repeatedly or concatenate everything into one big string first.writelines(list_of_strings)— takes an iterable (like a list) of strings and writes each one sequentially. It does not add newlines automatically — that's why the original code already has\nat the end of each string in the list.
The question asks you to mentally run the code after changing writelines(lines) to write(lines). Let's trace what actually happens.
Step-by-Step Trace
| Step | Code | What Happens |
|---|---|---|
| 1 | myobject = open("myfile.txt", 'w') | File opened in write mode. If myfile.txt exists, its content is erased. If not, a new empty file is created. |
| 2 | lines = ["Hello everyone\n", "Writing #multiline strings\n", "This is the #third line"] | A list of three strings is created in memory. The file is still empty. |
| 3 | myobject.write(lines) | Error occurs here. write() expects a single string, but lines is a list. Python raises a TypeError. |
| 4 | myobject.close() | This line is never reached because the program crashed at step 3. The file remains open (though Python will eventually close it on garbage collection, it's bad practice to rely on that). |
A common pitfall is thinking write() can accept a list just because writelines() does. They are not interchangeable — write() takes exactly one string argument. If you want to write multiple lines with write(), you must either loop over the list or join the strings first:
# Option 1: loop
for line in lines:
myobject.write(line) …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.