python2中print是个关键字,在python3中print是个函数
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
平常我们一般都只是传入value参数,但其实print函数还提供里很多功能
sep参数
当我们需要打印多个value时,会根据sep参数来分隔,sep默认是一个空格
>>> print('a', 'b')
a b
>>> print('a', 'b', sep='')
ab
end参数
end参数默认为\n,也就是print函数默认打印完后换行
>>> print('END', end='!\n')
END!
file参数
file参数是print函数结果的输出端,默认sys.stdout,也就是代表运行脚本的窗口。
>>> f = open('tem.text', 'r+')
>>> print('test', file=f)
>>> f.close()
tem.text
test
flush参数
flush参是和file参数配套使用的,flush参数默认为False,因为print其实是将文本数据先输出到内存,在file close的时候会把内存里的数据一次性flush到文件里。而开启flush后print就能把当前这次打印的数据从内存写到文件中
import time
f = open('tem.text', 'r+')
for i in range(10):
print(i, file=f)
time.sleep(1)
# 在循环中我们可以去不断打开tem.text文件,你会发现没有任何内容
f.close()
# 只有关闭文件后打开tem.text文件才有内容
开启flush
import time
f = open('tem.text', 'r+')
for i in range(10):
print(i, file=f, flush=True)
time.sleep(1)
# 在循环中我们可以去不断打开tem.text文件,你会发现内容在不断的追加
f.close()