Python で print の出力先をファイルに変える2019年05月23日 13時52分11秒

sys.stdout にファイルを指定する事で、print 関数の出力先を一時的に変える事ができる。
import sys
with open(‘/tmp/hello.txt’, 'w') as f:
    sys.stdout = f
    print “Hello world.“