Python - File Reading and Writing Strategies
Find the error in this code that tries to write lines to a file efficiently:
lines = ['line1\n', 'line2\n', 'line3\n']
file = open('output.txt', 'w')
for line in lines:
file.write(line)
file.close()Find the error in this code that tries to write lines to a file efficiently:
lines = ['line1\n', 'line2\n', 'line3\n']
file = open('output.txt', 'w')
for line in lines:
file.write(line)
file.close()with risks leaving it open if error occurs before close().with open() for automatic closingwith open('output.txt', 'w') as file: ensures file closes safely.15+ quiz questions · All difficulty levels · Free
Free Signup - Practice All Questions