Good Code
The good version scopes the file lifetime with with, includes an encoding, and closes the file even if writing a row fails.
Lesson 06
Use context managers so file handles and other resources close even when work fails.
def write_review_export(path, rows):
with open(path, "w", encoding="utf-8") as file:
for row in rows:
file.write(f"{row.id},{row.status}\n")def write_review_export(path, rows):
file = open(path, "w")
for row in rows:
file.write(f"{row.id},{row.status}\n")
file.close()The good version scopes the file lifetime with with, includes an encoding, and closes the file even if writing a row fails.
The bad version relies on manual close(). An exception in the loop can leave the file open, and the default encoding depends on the environment.