- This topic is empty.
-
AuthorPosts
-
December 16, 2025 at 12:46 am #5867
Answer:
Yes.write()is a method in Python.
❓ Q2.
write()is a method of which class?Answer:
write()is a method of the file object returned by theopen()function.In this line:
with open(self.__filename, "w") as f:open()returns a file objectfis an instance of Python’s file-handling class- In text mode (
"w"), this object belongs to the internal class:
_io.TextIOWrapper
❓ Q3. What exactly is
finf.write()?Answer:
fis a file object, not a string or variable container.So when you write:
f.write("Hello")You are calling the
write()method of the file object.
❓ Q4. What does the
write()method do?Answer:
Thewrite()method:- Writes a string to a file
- Returns the number of characters written
Example:
count = f.write("Hello\n") print(count) # Output: 6
❓ Q5. Why does
write()require a string?Answer:
Because files opened in text mode ("w") only accept strings.This works:
f.write("123")This fails:
f.write(123) # TypeError
❓ Q6. In this code, what does
line = [name] + numbersdo?line = [name] + numbersAnswer:
It creates a list where:nameis the first elementnumbersis a list of values added after it
Example:
name = "Raj" numbers = ["123", "456"] line = ["Raj", "123", "456"]
❓ Q7. Why is
";".join(line)used beforewrite()?Answer:
Becausejoin():- Converts a list of strings into one single string
- Inserts
;between each element
Example:
";".join(["Raj", "123", "456"])Output:
Raj;123;456
❓ Q8. Why is
"\n"added at the end?f.write(";".join(line) + "\n")Answer:
\nadds a new line, so each phonebook entry appears on a separate line in the file.
❓ Q9. What happens if
numberscontains integers instead of strings?Answer:
The code will fail, becausejoin()only works with strings.❌ This will raise an error:
numbers = [123, 456] ";".join(numbers)✅ Correct approach:
line = [name] + list(map(str, numbers))
❓ Q10. Can you summarize the full line in simple words?
f.write(";".join(line) + "\n")Answer:
This line:Converts a list into a semicolon-separated string and writes it as one line in a file.
✅ Final takeaway (one-liner)
write()is a method of the file object returned byopen(), and it is used to write strings to files. -
AuthorPosts
- You must be logged in to reply to this topic.

