[Tutor] Append mode dilemma
rabidpoobear at gmail.com
Wed Dec 9 21:58:15 CET 2009
On Wed, Dec 9, 2009 at 2:46 PM, Lie Ryan <lie.1296 at gmail.com> wrote:
> On 12/10/2009 6:12 AM, Luke Paireepinart wrote:
>> This won't work unless you have STDOUT redirected to your file. It
>> would be better just to do
>> fobj.write('\n'.join(all) + '\n')
> except that if you're joining a very long string, you'll have python copy
> the whole string again.
> better to just redirect print
> print >> fobj, '\n'.join(all)
I'm sorry, but this just seems like kind of an unreadable way to do this.
You're implicitly relying on print adding a newline to the end of every
You could also just append an empty string to the end of "all" and thus
another newline would be added.
Either approach is less clear than the concatenation. I guess it just
depends on the size of your string.
The most readable approach while still being efficient would probably be
just to write a newline after the previous write.
Then it's still absolutely clear that you're trying to get a newline there
and it's not a side-effect of some other function.
> but since this is a file object we're talking about, you can write while
> getting user input.
> with open(...) as fobj:
> entry = ''
> while entry != '.'
> Again, the file will only have a newline at the end in this situation
because you're relying on the implicit newline created by reading in the
user's string from raw_input.
So I don't think this is a good example to give in this situation, because
as soon as the user starts splitting / stripping / parsing raw_input and
then trying to write it back out
they're going to get confused.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor