In normal work, sometimes we need to save the console output to a file
1. Command line with> overwrite and >> append write
for i in range(10000): print(i)
#Write the console output override to the file python myprint.py> myprint.txt
#Append the console output to the file python myprint.py >> myprint.txt
2. Output sys.stdout to a file
import sys import time f=open("myprint.txt","w+") sys.stdout=f for i in range(1000): print(i*9)
Disadvantages: can only be saved to a file, but the console has no output
3. Use the file parameter in the print function
import sys import time f=open("myprint.txt","w+") for i in range(100): print("--{}--".format(i**2),file=f,flush=True) print("--{}--".format(i ** 2),file=sys.stdout) time.sleep(0.5)
Save the output from the console to a file instantly
The file parameter in the print function, file = f, output to file; file = sys.stdout, output to terminal; flush = True, instant refresh
4. Implement with classes
import sys class Logger(object): def __init__(self, filename='default.log', stream=sys.stdout): self.terminal = stream self.log = open(filename, 'a') def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): pass sys.stdout = Logger(stream=sys.stdout) # now it works print('print something') print("output")