如何将打印输出重定向到 TXT 文件 [英] How to redirect the output of print to a TXT file
问题描述
我已经搜索了 Google、Stack Overflow 和我的 Python 用户指南,但没有找到一个简单可行的答案.
I have searched Google, Stack Overflow and my Python users guide and have not found a simple, workable answer for the question.
我在 Windows 7 x64 机器上创建了一个文件 c:\goat.txt 并试图将test"打印到文件中.我根据 StackOverflow 上提供的示例尝试了以下操作:
I created a file c:\goat.txt on a Windows 7 x64 machine and am attempting to print "test" to the file. I have tried the following based on examples provided on StackOverflow:
此时我不想使用日志模块,因为我从文档中不明白基于二进制条件创建一个简单的日志.打印很简单,但是如何重定向输出并不明显.
At this point I don't want to use the log module since I don't understand from the documentation of to create a simple log based upon a binary condition. Print is simple however how to redirect the output is not obvious.
一个简单、清晰的例子,我可以输入到我的 interperter 中是最有帮助的.
A simple, clear example that I can enter into my interperter is the most helpful.
此外,对信息性网站的任何建议(不是 pydocs)表示赞赏.
Also, any suggestions for informational sites are appreciated (NOT pydocs).
import sys
print('test', file=open('C:\\goat.txt', 'w')) #fails
print(arg, file=open('fname', 'w')) # above based upon this
print>>destination, arg
print>> C:\\goat.txt, "test" # Fails based upon the above
推荐答案
如果您使用的是 Python 2.5 或更早版本,请打开文件,然后在重定向中使用文件对象:
If you're on Python 2.5 or earlier, open the file and then use the file object in your redirection:
log = open("c:\\goat.txt", "w")
print >>log, "test"
如果您使用的是 Python 2.6 或 2.7,则可以将打印用作函数:
If you're on Python 2.6 or 2.7, you can use print as a function:
from __future__ import print_function
log = open("c:\\goat.txt", "w")
print("test", file = log)
如果您使用的是 Python 3.0 或更高版本,那么您可以省略将来的导入.
If you're on Python 3.0 or later, then you can omit the future import.
如果你想全局重定向你的打印语句,你可以设置 sys.stdout:
If you want to globally redirect your print statements, you can set sys.stdout:
import sys
sys.stdout = open("c:\\goat.txt", "w")
print ("test sys.stdout")
这篇关于如何将打印输出重定向到 TXT 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!