博客
关于我
【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

你可能感兴趣的文章
MySQL 添加索引,删除索引及其用法
查看>>
mysql 状态检查,备份,修复
查看>>
MySQL 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>
mysql 索引
查看>>
MySQL 索引失效的 15 种场景!
查看>>
MySQL 索引深入解析及优化策略
查看>>