【python】输出到文件, f.write与print

将控制台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文件
>>>
1
2
3
...
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()

>>>
1
2
3
...
100

##########################
# ---------py3.x-------- #
f = open('log.txt','w')
for i in range(100):
    print(str(i), file=f)
f.close()

>>>
1
2
3
...
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
pic from pexels.com

发布了357 篇原创文章 · 获赞 307 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/u014636245/article/details/103504758
今日推荐