[Tutor] creating files with python and a thanks
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sat, 16 Feb 2002 23:45:44 -0800 (PST)
On Sat, 16 Feb 2002, Sheila King wrote:
> On Sun, 17 Feb 2002 03:59:05 +0000, Eve Kotyk <e.kotyk@shaw.ca> wrote
> about Re: [Tutor] creating files with python and a thanks:
>
> > > f = open('myfile.mbg', 'w')
> > > f.write('this is my file\nmy stuff\nis in\nmy\nfile')
> > > f.close()
> > >
> > This is interesting to me for my project. So if instead of f.write
> > ('this is my file...., ..) I wanted to write the whole input and output
> > of a function to a file how would I do that?
Also, just as we can 'print' out the results of a function on screen:
###
>>> def square(x): return x * x
...
>>> print "The square of 42 is", square(42)
The square of 42 is 1764
###
We can also 'print' to a file, like this:
###
>>> f = open('output.txt', 'w')
>>> print >>f, "The square of 42 is", square(42)
>>> f.close()
>>> print open('output.txt').read()
The square of 42 is 1764
###
In this case, we can use the 'print >>file' statement, and since you're
already familiar with how 'print' works, this should be a good way of
doing file output.
(On the other hand, I can't say that I _like_ the syntax of this extended
'print' statement; I would have much preferred something like:
fprint f, "The square of 42 is", square(42)
because at least it avoids a semantic conflict with the shift-right
operator, and seems to fix my internal model of Python. Has anyone written
a PEP request to change the syntax of 'print >>file' yet?)
Ignore my grumbling. *grin* Anyway, hope this helps!