如何在Windows中将输出导入txt文件的Python代码

13 投票
6 回答
74585 浏览
提问于 2025-04-16 10:47
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系统上)?

6 个回答

7

你可以在你的脚本中直接把 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
19

在控制台上,你可以这样写:

python script.py > out.txt

如果你想用Python来做,那你可以这样写:

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

显然,这只是一个简单的例子。你在with块里面肯定会做更多的事情。

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()

撰写回答