Directing print output to a .txt file

后端 未结 7 2500
北荒
北荒 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:25

    Suppose my input file is "input.txt" and output file is "output.txt".

    Let's consider the input file has details to read:

    5
    1 2 3 4 5
    

    Code:

    import sys
    
    sys.stdin = open("input", "r")
    sys.stdout = open("output", "w")
    
    print("Reading from input File : ")
    n = int(input())
    print("Value of n is :", n)
    
    arr = list(map(int, input().split()))
    print(arr)
    

    So this will read from input file and output will be displayed in output file.

    For more details please see https://www.geeksforgeeks.org/inputoutput-external-file-cc-java-python-competitive-programming/

提交回复
热议问题