博客
关于我
【python】输出到文件, f.write与print
阅读量:272 次
发布时间:2019-03-01

本文共 1477 字,大约阅读时间需要 4 分钟。

将控制台print的信息输出到文件,py2.x可以利用流输入符>>,py3.x可以使用file参数

1.输出到文件 I/O

将信息输出到文件最直接的方法是使用文件I/O:

f = open('log.txt','w')for i in range(100):    f.write(str(i)+'\n')f.close()# 生成log.txt文件>>>123...100

2.输出到文件 print 函数

print函数除了打印到控制台,同时还提供了输出到文件的功能,其默认输出文件是sys.stdout,意味着控制台输出。如果感兴趣可以看更详细的.

########################### ---------py2.x-------- #f = open('log.txt','w')for i in range(100):    # print >> f, str(i)+'\n'    print >> f, str(i)    #print函数加了\n,不需要再加了f.close()>>>123...100########################### ---------py3.x-------- #f = open('log.txt','w')for i in range(100):    print(str(i), file=f)f.close()>>>123...100

3.print doc

最后给出print函数的参考文档,除了需要打印的值value外,还有sep分割符号,en d结束符,flush强制流输出,file目标文件等四个参数。

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."""
ref:
https://www.python.org/dev/peps/pep-3105/#id9
https://docs.python.org/2/reference/simple_stmts.html#print
https://zhuanlan.zhihu.com/p/86859011
https://blog.csdn.net/u013783249/article/details/80669634
https://blog.csdn.net/u012145971/article/details/81207303
https://blog.csdn.net/liweiblog/article/details/53198468
https://blog.csdn.net/yageeart/article/details/38386121

https://images.pexels.com/photos/1742926/pexels-photo-1742926.jpeg

你可能感兴趣的文章
Metasploit Web服务器渗透测试实战
查看>>
MFC模态对话框和非模态对话框
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB可视化客户端管理工具之NoSQLbooster4mongo
查看>>
Mongodb学习总结(1)——常用NoSql数据库比较
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
mongodb定时备份数据库
查看>>
mppt算法详解-ChatGPT4o作答
查看>>
mpvue的使用(一)必要的开发环境
查看>>
MQ 重复消费如何解决?
查看>>
mqtt broker服务端
查看>>
MQTT 保留消息
查看>>
MQTT 持久会话与 Clean Session 详解
查看>>
MQTT工作笔记0007---剩余长度
查看>>
MQTT工作笔记0009---订阅主题和订阅确认
查看>>
Mqtt搭建代理服务器进行通信-浅析
查看>>
MS Edge浏览器“STATUS_INVALID_IMAGE_HASH“兼容性问题
查看>>
ms sql server 2008 sp2更新异常
查看>>