我在python中有以下脚本。 我在范围内(10000): 打印我
上面的python代码在控制台上打印i的值,从0到9999。
现在我想将脚本的输出直接路由到外部文件 在linux上,我可以使用以下命令
完成它$ python python_script.py> python_out.txt
Windows 7,IDLE Python Shell和PyLab下的等效命令是什么?
此外,Above脚本打印0到9999之间的数字。我想拍摄输出的快照, 即我想将前85个记录/数字路由到out1.txt OR 我想将可被5整除的数字路由到out2.txt ,不更改实际脚本。
还提供Python文档以了解更多信息。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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