I needed to download a file within a python program, someone told me to do this.
source = urllib2.urlopen("http://someUrl.com/somePage.html").read()
open("/path/to/someFile", "wb").write(source)
It working very well, but I would like to understand the code.
When you have something like
patatoe = 1
Isn’t a variable?
and when you have a something like:
blabla()
isn’t to define a function?
Please, I would LOVE to understand correctly the code.
You define a function using the
defkeyword:Without it, you are simply calling the function.
open(...)returns a file object. which you then use to write the data out. It’s practically the same as this:It isn’t quite the same, though, since the variable f holds onto the file object until it goes out of scope, whereas calling
open(...).write(source)creates a temporary reference to the file object that disappears immediately afterwrite()returns. The consequence of this is that the single-line form will immediately flush and close the file, while the two-line form wil keep the file open — and possibly some or all of the output buffered — untilfgoes out of scope.You can observe this behaviour in the interactive shell:
Now, without exiting the interactive shell, open another terminal window and check the contents of xxx and yyy. They’ll both exist, but only yyy will have anything in it. Also, if you go back to Python and invoke
f = Noneordel f, you’ll find that xxx has now been written to.