Bird
0
0

Which of the following is the correct syntax to write the string 'Hello' to a file named 'greet.txt'?

easy📝 Syntax Q12 of 15
Python - File Handling Fundamentals
Which of the following is the correct syntax to write the string 'Hello' to a file named 'greet.txt'?
Awith open('greet.txt', 'w') as file: file.write('Hello')
Bwith open('greet.txt', 'a') as file: file.read('Hello')
Copen('greet.txt', 'w').read('Hello')
Dfile = open('greet.txt', 'r'); file.write('Hello'); file.close()
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct file mode and method

    To write data, use 'w' mode and the write() method inside a with block for safety.
  2. Step 2: Check each option

    file = open('greet.txt', 'r'); file.write('Hello'); file.close() uses 'r' mode which is read-only, so write() will fail. open('greet.txt', 'w').read('Hello') uses read() instead of write(). with open('greet.txt', 'a') as file: file.read('Hello') uses read() and 'a' mode but tries to read data, which is incorrect. with open('greet.txt', 'w') as file: file.write('Hello') correctly uses 'w' mode and write() inside a with block.
  3. Final Answer:

    with open('greet.txt', 'w') as file: file.write('Hello') -> Option A
  4. Quick Check:

    Use with + 'w' + write() to save text [OK]
Quick Trick: Use with open(filename, 'w') and write() to save text [OK]
Common Mistakes:
  • Using 'r' mode when writing
  • Calling read() instead of write()
  • Not closing the file or missing with block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes