-6

How do we move the output of this script into a text file?

 k = raw_input("Enter the keyword:")
 if __name__ == "__main__":
     sys.path.append("./BeautifulSoup")
     from bs4 import BeautifulSoup

     opener = urllib2.build_opener()
     opener.addheaders = [('User-agent', 'Mozilla/5.0')]

     for start in range(0,2):
         url = "http://www.google.com.au/search?q="+ k +"&start=" + str(start*10)
         print url
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
Priya
  • 1,069
  • 1
  • 9
  • 8
  • Read ["Reading and Writing Files"](https://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files) in the tutorial. – Matthias Sep 25 '15 at 11:21
  • @Matthias you wrote it before i could enter my comment :D – Ja8zyjits Sep 25 '15 at 11:21
  • See [how to ask](http://stackoverflow.com/help/how-to-ask). Particularly [how to create a minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve). – Peter Wood Sep 25 '15 at 11:22

3 Answers3

2

If you don't want to use command line or write():

import sys
sys.stdout = open('output_file', 'w')
print 'test'

That way you can still use print()

Amir
  • 717
  • 2
  • 9
  • 21
  • I like this solution more, you don't need to do `file.write(...)` every time, although would probably still prefer command line option if it's a one-time-deal – akalikin Sep 25 '15 at 11:22
0

Just use standard shell redirection:

python your_script.py > output_file.ext

If you want to write to a file directly from the script without redirecting:

with open("output.ext", "w") as stream:
    print >>stream, "text"
user1514631
  • 1,183
  • 1
  • 9
  • 14
  • no sir..! i ask how to move into text file without executing command prompt..for example when i execute script.py this output directly move to text, dont show in command prompt...... – Priya Sep 25 '15 at 11:18
  • Thank you..! Its working....!!! – Priya Sep 25 '15 at 11:44
  • This doesn't work for me when I run Python.exe from within a CMD file - it creates a blank file and still outputs to the console. – PeterX Jan 24 '19 at 00:44
0

Just call the python script from the terminal like this:

python yourfile.py > yourtextfile_with_output.txt

For outputting without command line use:

text_file = open("Output.txt", "w")
text_file.write("your output here")
text_file.close()
Niki van Stein
  • 10,564
  • 3
  • 29
  • 62