tags:

views:

401

answers:

2

Hello!

Can you tell me how to code a Python script which reads a file from an external server? I look for something similar to PHP's file_get_contents() or file() function.

It would be great if someone could post the entire code for such a script.

Thanks in advance!

+12  A: 

The entire script is:

import urllib
content = urllib.urlopen('http://www.google.com/').read()
Jarret Hardie
You might want to use urllib2, which is similar but offers numerous add-on-features for security and cookie handling.
S.Lott
S.Lott is right: urllib2 offers a similar interface, though greater capability. In Python 3, the distinction between urllib and urllib2 is effectively gone, merged into a new urllib module with a specialized 'request' and 'error' areas.
Jarret Hardie
For python 2, content = urllib.urlopen('http://www.google.com/').read() and content = urllib2.urlopen('http://www.google.com/).read() are equivalent, until you need cookies or auth, in which case urllib2 is much, much, vastly, better
Jarret Hardie
Thanks, then urllib is enough for me.
+5  A: 

better would be the same as Jarret's code, but using urllib2:

import urllib2
content = urllib2.urlopen('http://google.com').read()

urllib2 is a bit newer and more modern. Doesn't matter too much in your case, but it's good practice to use it.

Aaron