Simple print, much secret

小小print,大大content

print是Python的内置方法之一,也是我们最常用的打印、调试的方式。我们来看看builtins.py中print的源码:

def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.
    """
    pass

*args: 这个参数决定了print能同时打印多个值。

print(1, 2, 3)

>>> 1  2  3

sep: 这个参数决定了当print打印多个值时,值中间的连接字符。他的默认值是一个空格。也就是你打印多个值的时候,这些值会以一个空格分开,如上。

print(1, 2, 3, sep='|')
print(1, 2, 3, sep='ppp')
print(1, 2, 3, sep='哈哈哈')

>>> 1|2|3
>>>1ppp2ppp3
>>>1哈哈哈2哈哈哈3

end: 这个参数决定了打印结束时,用什么字符串接在打印的值的末尾,默认是一个'\n'的换行符。

print(1,2,3, end='|')
>>> 1 2 3|

print(1,2,3, end='哈哈哈')
>>> 1 2 3哈哈哈

当end='\r'的时候,打印完一行的时候,光标会返回到这一行的行首。第二次打印时,会覆盖第一次打印的值。

print(1, end='\r')
print(2, end='\r')
print(3, end='\r')
print(4, end='\r')
print(5, end='\r')

>>> 5

file:重头戏,当这个参数传入一个文件句柄的时候,能将print的内容,写入到这个文件。

f = open('1.txt', mode='r+', encoding='utf-8')
print('我是帅比', file=f)
f.close()
>>>当前目录下的文件1.txt,里面的内容就变成了 '我是帅比'

前提:文件句柄f必须是可写入的,如果文件句柄f是r的话,就会报错。

flush: Python中flush是把文件从内存缓冲区buffer中,强制刷新到硬盘中的一种方法。

文件操作写入时,会先把内容写入到内存buffer(缓冲区)中,等到文件关闭时,就将缓冲区的内容写入到磁盘。

有时候你需要在文件关闭前,将内容写入到磁盘。这时候就需要用到flush。

 

posted @ 2019-07-13 12:22  KbMan  阅读(288)  评论(0编辑  收藏  举报