官方文档
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就有了。