Skip to main content

Section 2.4 File I/O

Writing a CSV file is easy; just write a formatted line with each row of data that you want:

Note that unlike print(), you'll need to explicitly include the newline character (\n) at the end of each line; otherwise all the lines just run together.

Logging errors to a file can be done similarly:

log = open("errorlog.txt", "a") # Use "append" mode to add to the end

try:
    # Some dangerous things that might throw exceptions

except Exception as e:
    log.write(f"Error: {e}\n")
    # Anything else to clean up/recover from the error