将控制台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.
"""