print(obj)实质就是调用sys.stdout.write(obj+’\n’)
sys.stdout是python中标准输出流
print()重定向到某个指定文件:
给sys.stdout赋值,修改它的指向
import sys
sys.stdout = open('test.txt','w')
print('Hello world')
从结果图中可以看出,执行test_print.py
文件时没有结果输出,然后再看test.txt
文件,可以看到输出到了该文件中
指定输出对象print()怎么恢复原本的终端输出
import sys
temp = sys.stdout
sys.stdout = open('test.txt','w')
print('hello world')
sys.stdout = temp #恢复默认映射关系
print('nice')
通过该结果图可以发现,修改完sys.stdout
后,终端即可显示。
print()与sys.stdout.write()区别
-
stdout只能输出字符串,如果要输出数字,也需要先转成字符串形式的;print可以直接输出各种类型。
-
stdout输出结果后不自动换行;print会自动换行。
-
print默认调用了sys.stdout.write()方法将输出打印到控制台,也可通过file参数将输出打印到其他文件中
f = open(‘test.txt’,‘a’)
print(‘this is a test’,file=f)