Writing to a file

cassiope fpm at u.washington.edu
Fri Mar 25 11:25:58 EDT 2011


On Mar 25, 8:07 am, <jyoun... at kc.rr.com> wrote:
> Just curious how others view the 2 examples below for creating and
> writing to a file in Python (in OS X).  Is one way better than the other?  
> If it was a large amount of text, would the 'os.system' call be a bad
> way to do it?
>
> Thanks.
>
> Jay
>
>
>
> >>> f = open('~/Desktop/test.txt', 'w')
> >>> f.write('testing 1... 2... 3...')
> >>> f.close()
>
> >>> import os
> >>> os.system('echo "Testing a... b... c..." > "~/Desktop/test2.txt"')
> 0
>
>

I personally consider each use of os.system(..) as something that
needs to be eliminated.
Maybe 'echo' isn't too bad... but (for example) is it subject to
limited argument lengths?
Does it perform differently on different OSs?  And if it's not
something intrinsic to the
OS, might there be 'PATH' issues: where is the called program?
Finally, there may be
some security issues (in general) though perhaps not in your specific
example.

Of course, if speed is a real issue there may be some value in
buffering a long string
before using whatever method to save it in a file.  OTOH these
functions usually include
system buffering (which the incremental os.system(..) call clearly
won't have).

Hope that helps...



More information about the Python-list mailing list