import itertools
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
print (variation_string)
import sys # Need to have acces to sys.stdout
fd = open('foo.txt','w') # open the result file in write mode
old_stdout = sys.stdout # store the default system handler to be able to restore it
sys.stdout = fd # Now your file is used by print as destination
print 'bar' # 'bar' is added to your file
sys.stdout=old_stdout # here we restore the default behavior
print 'foorbar' # this is printed on the console
fd.close() # to not forget to close your file
import itertools
file = open('out.txt', 'w')
variations = itertools.product('abc', repeat=3)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
file.write(variation_string)
file.close()
您还可以将
stdout
重定向到脚本中的文件,因为print
默认情况下会写入sys.stdout
文件处理程序。Python提供了一种简单的方法:在控制台上,您可以编写:
如果你想用Python来完成,那么你可以写:
显然这只是一个微不足道的例子。很明显你会在with街区做更多的事。
如果是我,我会使用上面的David Heffernan方法将变量写入文本文件(因为其他方法需要用户使用命令提示符)。
相关问题 更多 >
编程相关推荐