[Tutor] file read and write
Alan Gauld
alan.gauld at btinternet.com
Tue Sep 11 11:33:55 CEST 2007
"le dahut" <le.dahut at laposte.net> wrote
>I noticed that it is possible to write this :
> """
> file('/tmp/myfile', 'w').write('Hello world\n')
> contnt = file('/tmp/sourcefile').read()
> """
Yes, it just creates temporary objects and relies on
garbage collection to close/dispose of them.
> instead of :
> """
> fh = file('/tmp/myfile', 'w')
> fh.write('Hello world\n')
> fh.close()
>
> fh = file('/tmp/sourcefile')
> contnt = fh.read()
> fh.close()
> """
>
> is there a reason not to use the first example ?
Not really although its rather limited in what it can do
for you. Also error handling will not be as robust since
you can't check that the file was/was not created.
But if you just want a very short file it's fine and in
fact you will often see examples of
s = open('foo.txt').read()
in code, it is quite common, more so than the
write version.
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list