2011-01-28 27 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プラットフォーム)にリダイレクトするにはどうすればよいですか?あなたが書くでしょうコンソールからWindowsのpythonで出力をtxtファイルに出力する方法

+0

ステップ1は、コードを適切にフォーマットすることです。 '{}'ボタンを使用してください。 –

+0

@ S.Lottなぜですか?それはちょうど意味がありません – bicycle

答えて

1

OUTPUT.TXTファイルにprogram.pyの出力を格納します(他の方法ではユーザーがコマンドプロンプトを使用する必要があるため)。 printsys.stdoutファイルハンドラに、デフォルトでは書き込みとして

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ブロックの中でより多くのことを行うでしょう。ウィンドウのコマンド・プロンプトで

2

、このコマンドは、それが私だったら、私はテキストファイルにあなたの変数を記述するために、上記のデビッドHeffernanののメソッドを使用します

python program.py > output.txt 
+0

上記のプログラムへの出力は、クラスタ化された状態のようです:: aaaaabaacabaabbabcacaacbaccbaababbacbbabbbbbcbcabcbbcccaacabcaccbacbbcbcccaccbccc ////// Sirは出力が行の後の行にあるようにプログラムを修正できますか?出力の最初の行はaaaになり、次の行はaabになり、次はaacなどになります....ありがとう – user593908

1

あなたのスクリプトの中で直接ファイルへ>>

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

print >> log, variation_string 

log.close() 
+0

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

5

ます。また、リダイレクトも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

Windowsのバグを気にかけている場合 - [スクリプトの名前だけを使用してWindowsでPythonスクリプトを実行すると出力をリダイレクトできません](http://stackoverflow.com/questions/3018848/)。また、標準出力用のデフォルトのシステムハンドラは 'sys .__ stdout__'に格納されていますので、以前に設定したものに戻す必要がなければ' sys.stdout'を保存する必要はありません。 –

0

拡張

David's answerにあなたが実行するPyCharm

Go]を使用している場合 - > [編集設定] - > [ログ - - >チェックマークコンソールに保存 ファイルに出力 - >完全パスを入力 - >適用

Screenshot

関連する問題