with closes the file for you, when the indented block is exited. ~ isn't cross-platform at all, in fact it's not precisely python, though os.path.expanduser understands it.
AFAIK, the jury's still out on whether the /'s in pathnames as directory separators are portable. I know they work on *ix and Windows (in API's since DOS 2.0 when a directory hierarchy was introduced), but what about Python on MacOS 9, VMS, RiscOS, etcetera? I heard years ago on comp.lang.python that Python (not just the underlying OS, as above, but Python too) would treat / as a directory separator irrespective of what the underlying OS thought of it, but I'm having difficulty finding more than tangential references to this idea now. On Fri, Mar 25, 2011 at 6:39 PM, Littlefield, Tyler <ty...@tysdomain.com>wrote: > > with open(test_absname, 'w') as test: > what's the difference in that and test = ...? I can see why you mentioned > the os.path for cross-platform, but I don't understand why someone would use > with over =. > > On 3/25/2011 7:11 PM, eryksun () wrote: > >> On Friday, March 25, 2011 11:07:19 AM UTC-4, jyou...@kc.rr.com wrote: >> >>> f = open('~/Desktop/test.txt', 'w') >>>>>> f.write('testing 1... 2... 3...') >>>>>> f.close() >>>>>> >>>>> Consider using "with" to automatically close the file and os.path for >> cross-platform compatibility: >> >> import os.path >> user_home = os.path.expanduser('~') >> test_absname = os.path.join(user_home, 'Desktop', 'test.txt') >> >> with open(test_absname, 'w') as test: >> test.write('testing 1... 2... 3...') > >
-- http://mail.python.org/mailman/listinfo/python-list