You define a function using the def
keyword:
def f():
...
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:
f = open(...)
f.write(source)
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 after write()
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 — until f
goes out of scope.
You can observe this behaviour in the interactive shell:
>>> f = open('xxx', 'w')
>>> f.write('hello')
>>> open('yyy', 'w').write('world')
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 = None
or del f
, you'll find that xxx has now been written to.