2011-01-28 102 views
6
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平臺上)?如何直接輸出到python窗口中的txt文件

+0

第1步是正確格式化你的代碼。請使用`{}`按鈕。 – 2011-01-28 14:06:05

+0

@美國洛特爲什麼呢?這只是沒有任何意義 – bicycle 2013-03-30 06:02:16

回答

1

如果是我,我會用上述大衛赫弗南的方法,您的變量寫入文本文件(因爲其他方法需要用戶使用命令提示符)。

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

從控制檯你可以這樣寫:

python script.py > out.txt 

如果你想這樣做在Python那麼你可以這樣寫:

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

顯然,這只是一個簡單的例子。你會明顯在with block中做更多的事情。

2

在窗口的命令提示符,這個命令將program.py的輸出存儲到文件output.txt的

python program.py > output.txt 
+0

了出來放到上面的程序就像是一個聚集狀態:: aaaaabaacabaabbabcacaacbaccbaababbacbbabbbbbcbcabcbbcccaacabcaccbacbbcbcccaccbccc //////先生你能修改程序,以使輸出將是一行行之後是輸出的第一行是aaa,下一行是aab,下一行是aac,依此類推......謝謝 – user593908 2011-05-16 12:43:24

1

您可以使用>>

log = open("test.log","w") 

print >> log, variation_string 

log.close() 
+0

import itertools file = open('out.txt','w') 變化= itertools.product( 'ABC',重複= 3) 爲變化的變化: variation_string = 「」 字母中的變化: variation_string + =信 file.write(variation_string) file.close() \t 了出來放到上面的程序就像是一個羣集狀態:: aaaaabaacabaabbabcacaacbaccbaababbacbbabbbbbcbcabcbb //////先生,你能修改程序,以使輸出將是線後面的線是的第一行輸出將是AAA和下一行是AAB和下一個將是AAC等..謝謝 – user593908 2011-05-16 12:52:15

5

您也可以重定向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 
0

擴展到David's answer

如果您正在使用PyCharm

去跑 - >編輯配置 - >日誌 - - >複選標記保存控制檯 輸出到文件 - >輸入完整路徑 - >應用

Screenshot