Hi friends!

    import urllib
    url = 'http://www.python.org'
    text = urllib.urlopen(url).read()

I have typed the code above on the terminal and in the next line with print text an html file printed there.
I want to send it to a text file, how can i do that?

This is how you post to a text file

f = open('url.txt', 'w') #Opens the file to write text

f.write(url) #Writes the file to the opened text file

As Andrae posted,but need to close file object.

f = open('url.txt', 'w') #Opens the file to write text
f.write(url) #Writes the file to the opened text file
f.close()

Or the best approch is to use with open(),no need to close file object.

import urllib

url = 'http://www.python.org'
text = urllib.urlopen(url).read()
with open('url.txt', 'w') as f:
    f.write(text)

Thank you @Andrae.

Thank you @snippsat.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.