如何将所有打印导出到 Python 中的 .txt 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13794873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to export all print to a .txt file in Python?
提问by dylan
Possible Duplicate:
Redirect stdout to a file in Python?
可能的重复:
将标准输出重定向到 Python 中的文件?
I've finally finished all the code for my project. Now I need all of the things that are labelled "print" to actually be exported into a .txt document. How would I go about doing that?
我终于完成了我项目的所有代码。现在我需要将所有标记为“打印”的内容实际导出到 .txt 文档中。我该怎么做?
采纳答案by jdi
I would not even approach this from a python-fix perspective, but simply redirect the output of running your python script:
我什至不会从 python-fix 的角度来解决这个问题,而是简单地重定向运行 python 脚本的输出:
python /path/to/script/myscript.py > /path/to/output/myfile.txt
Nothing has to change in your script, and all print statements will end up in your text file.
您的脚本中没有任何更改,所有打印语句都将在您的文本文件中结束。
回答by Aesthete
Redirect stdoutto a file.
重定向stdout到一个文件。
import sys
sys.stdout = open('log.txt', 'w')
print 'Write this to file.'
EDIT: if you are using this method, still close the file when you are done writing: sys.stdout.close()
编辑:如果您正在使用此方法,请在完成写入后仍关闭文件: sys.stdout.close()
回答by Diego Basch
1) open a file for writing:
1)打开一个文件进行写入:
f = open("file.txt", "w")
2) replace all your print statements by print >>f, for example:
2)用print >>f替换所有打印语句,例如:
print "hello"becomes print >>f, "hello
print "hello"变成 print >>f, "hello
3) close the file when you're done
3)完成后关闭文件
f.close()

