how to count lines in a file ?

Alex Martelli aleax at aleax.it
Thu Jul 25 10:45:23 EDT 2002


Michele Simionato wrote:

> Can somebody provide a simple example where the idiom
> 
> file(name,'w').write(something)
> 
> fails, in the sense that the file is not closed or something is not
> written ? I tried to hang the program with a memory overload

[alex at lancelot jython-2.1]$ jython
Jython 2.1 on java1.4.0_01 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>> open('aname','w').write('something\n')
>>>
[alex at lancelot jython-2.1]$ cat aname
[alex at lancelot jython-2.1]$ ll aname
-rw-rw-r--    1 alex     alex            0 Jul 25 16:41 aname
[alex at lancelot jython-2.1]$

I exited the interactive interpreter with a clean, normal
control-D, but as you see file aname was created but its
contents not written.

Any implementation of Python is perfectly free to choose
this behavior if it provides some other advantage.

If you KNOW your code will NEVER need to migrate to any
other implementation of Python except the one you can test
today, then you may choose to use implementation-dependent
behavior if it gives you some other important plus.

In most situations, however, including scripts MEANT to
be throw-away, I would suggest taking the tiny extra effort
to avoid implementation-depended behavior.  It's far from
impossible that you may want to use those scripts on some
other implementation of Python, and if they pervasively used
implementation-dependent behavior that the other impl. does
not supply, you'll get no sympathy whatsoever:-).


Alex




More information about the Python-list mailing list