[Tutor] about pyhton + regular expression
Paul Tremblay
phthenry@earthlink.net
Thu Mar 20 14:57:01 2003
On Thu, Mar 20, 2003 at 09:41:01AM -0800, Jeff Shannon wrote:
>
> It should also be noted that, in both new and older versions of Python,
> there's a special pseudo-iterator that can be used. If you use the
> standard idiom
>
> infile = open('file.txt')
> for line in infile.readlines():
> [...]
> infile.close()
>
> then the entire contents of the file is read into a list of lines. If
> the file is large, this may swamp available memory. You can use the
> special xreadlines() method instead --
>
> for line in infile.xreadlines():
> [...]
>
Nifty. I had been doing:
line_to_read = '1'
while line_to_read:
line_to_read = infile.readline()
> destroyed right away when the last reference for them is deleted -- it
> happens right away in the current implementation of CPython, but not in
> Jython, and it's not guaranteed in *any* implementation. Typically,
> with files that are read once and never written to, this won't matter
> much, but if you're reading in a file and then later writing to the same
> file, it could cause problems. I feel that it's a good habit to
> explicitly close files, whether strictly necessary or not, so that I
> don't have to worry about which circumstances may be problematic and
> which are safe.
I strongly second this. Even in CPython I have had problems when I
didn't close a file:
file_obj.close
I had meant to close the file, but forgot the parenthesis, and couldn't
figure out for the life of me why the rest of the program didn't work.
Paul
--
************************
*Paul Tremblay *
*phthenry@earthlink.net*
************************