如何在Windows中的python中将输出定向到txt文件

use*_*908 9 python

import itertools  

variations = itertools.product('abc', repeat=3)  
for variations in variations:  
    variation_string = ""  
    for letter in variations:  
        variation_string += letter  
    print (variation_string)  
Run Code Online (Sandbox Code Playgroud)

如何将输出重定向到txt文件(在Windows平台上)?

Dav*_*nan 16

从控制台你会写:

python script.py > out.txt
Run Code Online (Sandbox Code Playgroud)

如果你想用Python做,那么你会写:

with open('out.txt', 'w') as f:
    f.write(something)
Run Code Online (Sandbox Code Playgroud)

显然这只是一个微不足道的例子.你明显在with block中做了更多.


小智 6

您也可以stdout直接在脚本中重定向到您的文件print,默认情况下写入sys.stdout文件处理程序.Python提供了一种简单的方法:

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
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 1

如果是我,我会使用上面 David Heffernan 的方法将变量写入文本文件(因为其他方法需要用户使用命令提示符)。

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()
Run Code Online (Sandbox Code Playgroud)