博客
关于我
【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 多个表求多个count
查看>>
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>
mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
查看>>
MySQL 存储过程参数:in、out、inout
查看>>
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>
Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
查看>>
Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>