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