sys.stdout.write()

本文详细解析了Python中print()函数与sys.stdout.write()方法的区别,包括它们如何处理不同类型的数据,是否自动换行,以及如何将输出重定向到文件。同时介绍了如何恢复被重定向的print()函数到其默认行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值