Python-打印操作

93 阅读2分钟

文件对象方法

  • print默认把对象打印到stdout流,添加了一些自动化的格式.和文件方法不同,在使用打印操作的时候,不需要把对象转换为字符串.

标准输出流

  • stdout只是发送一个程序文本输出的默认的地方,加上标准输出流和错误流,它只是脚本启动时所创建的3种数据连接的一种,标准输出流通常映射到启动Python程序的窗口,除非它已经在操作系统的shell中重定向到一个文件或管道.
  • 由于标准输出流在Python中可以作为内置的sys模块中的stdout文件对象使用(sys.stdout),用文件的写入方法调用模拟print成为可能.然而,print很容易使用,这使得很容易将文本打印到其他文件或者流.
  • print是一个函数.无返回值.
>>> L=[1,2]
>>> L.append(3)
>>> L
[1, 2, 3]
>>> L=L.append(4)
>>> L
>>> print(L)
None
>>> 

  • print([object,...][,sep=' '][,end='\n'][,file=sys.stdout])
>>> print(x,y,z,sep='')
spam99['eggs']
>>> print(x,y,z,sep='$,')
spam$,99$,['eggs']
>>> print(x,y,z,end='>>>')
spam 99 ['eggs']>>>
>>> print(x,y,z,end='');print(x,y,z)
spam 99 ['eggs']spam 99 ['eggs']


打印流重定向

>>> print('Hello world')
Hello world
>>> 'Hello world'
'Hello world'
>>> import sys
>>> sys.stdout.write('hello world')
hello world11
>>> sys.stdout.write('hello world\n')
hello world
12

重定向输出流

>>> import sys
>>> sys.stdout=open('log.txt','a')
>>> x=1
>>> y='spam'
>>> z=[7,8]
>>> print(x,y,z)
>>> sys.stdout.close()

自动重定向

`\>>> log=open('log.txt','w')
>>> print(1,2,3,file=log)
>>> print(4,5,6,file=log)
>>> log.close()
>>> print(open('log.txt').read())
1 2 3
4 5 6
  • 这种print的扩展模式可用于错误消息打印到标准错误流sys.stderr.
>>> import sys
>>> sys.stderr.write(('Bad!'*8)+'\n')
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
33
>>> print('Bad!'*8,file=sys.stderr)
Bad!Bad!Bad!Bad!Bad!Bad!Bad!Bad!
>>>