Directing print output to a .txt file

后端 未结 7 2478
北荒
北荒 2020-11-27 13:03

Is there a way to save all of the print output to a txt file in python? Lets say I have the these two lines in my code and I want to save the print output to a file named

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 13:32

    Give print a file keyword argument, where the value of the argument is a file stream. We can create a file stream using the open function:

    print("Hello stackoverflow!", file=open("output.txt", "a"))
    print("I have a question.", file=open("output.txt", "a"))
    

    From the Python documentation about print:

    The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.

    And the documentation for open:

    Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

    The " a " as the second argument of open means "append" - in other words, the existing contents of the file won't be overwritten. If you want the file to be overwritten instead, use "w".


    Opening a file with open many times isn't ideal for performance, however. You should ideally open it once and name it, then pass that variable to print's file option. You must remember to close the file afterward!

    f = open("output.txt", "a")
    print("Hello stackoverflow!", file=f)
    print("I have a question.", file=f)
    f.close()
    

    There's also a syntactic shortcut for this, which is the with block. This will close your file at the end of the block for you:

    with open("output.txt", "a") as f:
        print("Hello StackOverflow!", file=f)
        print("I have a question.", file=f)
    

提交回复
热议问题