Python Practice Test
Python File Input and Output Questions and Answers
Which of the following is the most idiomatic and safest way to open a file for writing in Python, ensuring that it is always closed properly?
Select your answer
A
file = open('data.txt', 'w'); file.write('content'); file.close()
B
try: file = open('data.txt', 'w') file.write('content') finally: file.close()
C
with open('data.txt', 'w') as file: file.write('content')
D
def write_file(): file = open('data.txt', 'w') file.write('content') return file.close()
Hint