[Tutor] output formatting
spir
denis.spir at free.fr
Sat Apr 25 19:21:44 CEST 2009
Le Sat, 25 Apr 2009 11:02:47 -0400,
Matt Domeier <domeier at umich.edu> s'exprima ainsi:
> Hi Wayne,
>
> Yes, that should work perfectly, but it is in writing files that I'm
> having the problem. I'm still very new to python, so I only know to
> use something like filename.write(str(listname)) to write my list to a
> file..
> Is there a straightforward method of combining the ease of the print
> function setup that you suggested with write? Or could I somehow use
> the print function itself to write to the file (rather than just
> output to my shell/prompt)?
>
> Thanks!
I think you're confusing the writing function (file.write() or print) with the expression of the text to be written.
You can safely reuse the expression proposed by Wayne inside write():
filename.write( '\n'.join(['the quick brown fox', 'jumps over', 'the lazy dog']) )
The remaining difference is that print will implicitely add an '\n' (end-of-line).
Also (but this difference does not apply here), write() expects a string while print will silently convert to str whatever you pass it:
f = file("test", 'w')
try:
f.write(1)
except TypeError:
f.write("*** not a str ***")
f.write(str(1))
f.close()
f = file("test", 'r')
print f.read()
f.close()
==>
*** not a str ***
1
Denis
> Quoting W W <srilyk at gmail.com>:
>
> > On Fri, Apr 24, 2009 at 10:57 PM, Matt Domeier <domeier at umich.edu> wrote:
> >
> >> Hello,
> >>
> >> I have a series of lists that I need to output into files with a specific
> >> format. Specifically, I need to have line breaks after each entry of the
> >> list, and I need to do away with the ['..'] that accompany the data
> >> after I transform the list into a string. Can I simply append a '\n' to
> >> the end of all the list entries in order to enact line breaks?
> >>
> >
> > Is this what you're looking for?
> >
> > In [3]: print '\n'.join(['the quick brown fox', 'jumps over', 'the lazy
> > dog'])
> > the quick brown fox
> > jumps over
> > the lazy dog
> >
> > HTH,
> > Wayne
> >
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
------
la vita e estrany
More information about the Tutor
mailing list