user593908
user593908

Reputation: 143

how to direct output into a txt file in python in windows

import itertools  

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

How can I redirect output into a txt file (on windows platform)?

Upvotes: 13

Views: 76176

Answers (6)

Morse
Morse

Reputation: 9144

Extension to David's answer

If you are using PyCharm,

Go to Run --> Edit Configurations --> Logs --> Check mark Save console output to file --> Enter complete path --> Apply

Screenshot

Upvotes: 1

user473489
user473489

Reputation: 116

You may also redirect stdout to your file directly in your script as print writes by default to sys.stdout file handler. Python provides a simple way to to it:

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

Upvotes: 7

David Heffernan
David Heffernan

Reputation: 613511

From the console you would write:

python script.py > out.txt

If you want to do it in Python then you would write:

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

Obviously this is just a trivial example. You'd clearly do more inside the with block.

Upvotes: 19

YOU
YOU

Reputation: 123917

you may use >>

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

print >> log, variation_string

log.close()

Upvotes: 1

Adam
Adam

Reputation: 442

If it were me, I would use David Heffernan's method above to write your variable to the text file (because other methods require the user to use a command prompt).

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

Upvotes: 1

kefeizhou
kefeizhou

Reputation: 6552

In window command prompt, this command will store output of program.py into file output.txt

python program.py > output.txt

Upvotes: 2

Related Questions