print to a file instead of the screen

MateoGOP

Is there a way to make print write into a file? The article only shows the console.

5

Comments 4

Join the discussion

Already have an account? Log in

  1. BellaRossireplies: 2

    Yes, print has a file parameter:

    with open("log.txt", "a", encoding="utf-8") as f:
        print("Engine check OK", file=f)

    For real logging, look at the logging module later — it adds timestamps and levels.

    2
      1. SophieDev

        The "Logging instead of print" challenge shows the logging module step by step.

        -1
      2. CharlieH

        print(..., file=sys.stderr) is handy for error messages so they don't mix with normal output.

        1