sys.stdout.write()和print以及sys.stdout.flush()之间的区别

官方文档

1 “”"
2 sys.stdout.write(string)
3   Write string to stream.
4   Returns the number of characters written (which is always equal to the length of the string).
5
6 print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
7   Prints the values to a stream, or to sys.stdout by default.
8
9   Optional keyword arguments:
10   file: a file-like object (stream); defaults to the current sys.stdout.
11   sep: string inserted between values, default a space.
12   end: string appended after the last value, default a newline.
13   flush: whether to forcibly flush the stream.
14 “”"
sys.stdout.write()与print()之间的区别

①sys.stdout.write是将str写到流,原封不动,不会像print那样默认end=’\n’

②sys.stdout.write只能输出一个str,而print能输出多个str,且默认sep=’ '(一个空格)

③print,默认flush=False.

④print还可以直接把值写到file中

1 import sys
2 f = open(‘test.txt’, ‘w’)
3 print(‘print write into file’, file=f)
4 f.close()

sys.stdout.flush()的作用
flush是刷新的意思,在print和sys.stdout.write输出时是有一个缓冲区的。
比如要向文件里输出字符串,是先写进内存(因为print默认flush=False,也没有手动执行flush的话),在close文件之前直接打开文件是没有东西的,如果执行一个flush就有了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值