Skip to content
Exercises · Q6

Q.Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened in append mode.
"Welcome my class"
"It is a fun place"
"You will learn and play"

Rajasthan RbseTextbookSubjective· 3mImportance★★★★★
45% · 10/22 Questions
🔒 Locked · start free trial →

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 →

Use the write() method on a file object opened in append mode to add each line, ensuring newline characters are included.

Why write() is the right tool

When a file is opened in append mode ('a'), any data written to it is added at the end without overwriting existing content. The write() method sends a string to the file exactly as given — it does not automatically add line breaks. Since the question asks for three separate lines, you must explicitly include the newline character \n at the end of each string to ensure they appear on distinct lines in the file.

Alternatively, writelines() can write a list of strings in one call, but again, newlines must be part of each string.


Solution

Assuming the file hello.txt is already opened in append mode and assigned to a file object f, the commands are:

f = open('hello.txt', 'a')
f.write("Welcome my class\n")
f.write("It is a fun place\n")
f.write("You will learn and play\n")
f.close()

Key points:

  • 'a' mode positions the file pointer at the end; existing content remains intact.
  • \n is essential. Without it, all three strings would run together on a single line.
  • close() flushes the buffer and releases the file handle. Omitting it risks data loss if the program terminates unexpectedly.

Alternative: using writelines()

f = open('hello.txt', 'a')
lines = ["Welcome my class\n", "It is a fun place\n", "You will learn and play\n"]
f.writelines(lines)
f.close()

This is cleaner when you have multiple lines stored in a list.


Alternative: context manager (best practice)

with open('hello.txt', 'a') as f:
    f.write("Welcome my class\n")
    f.write("It is a fun place\n")
    f.write("You will learn and play\n")
``` …

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.