windows环境下python中直接输出到txt文件的方法

2024-04-27 15:53:53 发布

您现在位置: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)  

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


Tags: 文件inimporttxtforstringproduct重定向
3条回答

您还可以将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

在控制台上,您可以编写:

python script.py > out.txt

如果你想用Python来完成,那么你可以写:

with open('out.txt', 'w') as f:
    f.write(something)

显然这只是一个微不足道的例子。很明显你会在with街区做更多的事。

如果是我,我会使用上面的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()

相关问题 更多 >