打印print的另一种方式sys.stdout

>>> import sys
>>> tmp = sys.stdout
>>> sys.stdout=open('log.txt','a')
>>> print('cisco')
>>> print(1,2,3)
>>> sys.stdout.close()
>>> sys.stdout=tmp
>>> print('haha')
haha
>>> print(open('log.txt','rb').read())
b'welcome to haha\r\ncisco\r\n1 2 3\r\n'
>>> print(open('log.txt','r').read())
welcome to haha
cisco
1 2 3

>>> 

  tmp作用是保存当前的sys.stdout,修改了sys.stdout后能找回之前的sys.stdout,来让print能输出到屏幕

如果想用print实现把打印的内容导出到文件:

>>> x,y,z='haha',88,['python','ericsson']
>>> x
'haha'
>>> y
88
>>> z
['python', 'ericsson']
>>> print(x,y,z,sep='...!', file=open('data.txt','w'))
>>> print(x,y,z)
haha 88 ['python', 'ericsson']
>>> file.close()
>>> print(open('data.txt','r').read())
haha...!88...!['python', 'ericsson']

  在该目录下,会生成一个data.txt文件

 

posted @ 2019-07-12 14:47  月亮上的石头  阅读(683)  评论(0编辑  收藏  举报