0

我在 python 中有以下脚本。对于范围内的 i(10000):打印 i

上面的一段 python 代码在控制台上打印从 0 到 9999 的 i 值。

现在我想将脚本的输出直接路由到外部文件。
在 linux 上,我可以使用以下命令完成它

$ python python_script.py > python_out.txt

Windows 7、IDLE Python Shell 和 PyLab 下的等效命令是什么?

此外,上面的脚本打印从 0 到 9999 的数字。我想对输出进行快照,即我想将前 85 条记录/数字路由到 out1.txt 或者我想将可被 5 整除的数字路由到out2.txt 而不更改实际脚本。

还提供给我 Python 文档以了解更多信息。

4

3 回答 3

3
file1, file2 = "out1.txt", "out2.txt"
with open(file1,'w') as f1,open(file2,"w") as f2:
    for i in range(10000):
        if i < 85:
            f1.write("{0}\n".format(i))  # write to out1.txt
        if i%5==0:
            f2.write("{0}\n".format(i))  #write to out2.txt
        print i                 #write to stdout or python_out.txt in your case

并将此程序运行为:

$python python_script.py > python_out.txt
于 2013-05-05T12:41:16.870 回答
1

这是一个有点难看的代码,但您不必更改脚本。

class A:
    def __init__(self, filename, predicate=(lambda ln, v:True)):
        self.filename = filename
        self.lines = 0
    def write(self, text):
        if predicate(self.lines, text):
            with open(self.filename, 'a') as f:
                f.write(text)
        self.lines += text.count('\n')

用法:

import sys

def predicate(linenumber, text):
    if text.isdigit():
        if int(text) % 5:
            return False
    return True

sys.stdout = A('out1.txt', predicate)

for i in range(10000):
    print i
于 2013-05-05T12:52:21.750 回答
0

您必须打开一个文件并在其中写入,就像这样。

f = open('write_to_this_file.txt', 'w')
for i in xrange(10000):
    f.write(i + "\n")

这是更多信息http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

于 2013-05-05T12:37:52.503 回答