Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)  

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

like image 364
user593908 Avatar asked Jan 28 '11 13:01

user593908


People also ask

How do I save Python output to a text file?

First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do I output to a text file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do you create an output file in Python?

To create and write to a new file, use open with “w” option. The “w” option will delete any previous existing file and create a new file to write. If you want to append to an existing file, then use open statement with “a” option. In append mode, Python will create the file if it does not exist.


2 Answers

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.

like image 144
David Heffernan Avatar answered Oct 10 '22 01:10

David Heffernan


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
like image 44
user473489 Avatar answered Oct 10 '22 02:10

user473489