Writing to a file

Adam Tauno Williams awilliam at whitemice.org
Fri Mar 25 12:05:24 EDT 2011


On Fri, 2011-03-25 at 15:07 +0000, jyoung79 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?

Option#1

> >>> f = open('~/Desktop/test.txt', 'w')
> >>> f.write('testing 1... 2... 3...')
> >>> f.close()

Option#2

> >>> import os
> >>> os.system('echo "Testing a... b... c..." > "~/Desktop/test2.txt"')

Option#2 is weird and stupid.  

If something goes wrong making sense the error message in Option#2 is
going to be much harder than Option#1 - where opening the file in write
mode, and writing the file are discrete operations.  Also Option#2 is
going to be far more platform dependent, even shell dependent [Where
does "echo" come from?  What does "~" mean?].

Do things in discrete steps, and be explicit about what you are doing.
Option#2 fails both those requirements.




More information about the Python-list mailing list