newbie question...

Fredrik Lundh fredrik at pythonware.com
Wed Dec 29 06:53:12 EST 1999


Eugene Goodrich <bitbucket at isomedia.com> wrote:
> The example Justin Sheehy gave is certainly better most of the time,
> but if you feel you _must_ do it like that Perl code (say, you've got
> a 100 MB file you don't feel like putting into memory all at once),
> you can do this:
> 
> oFile = open ('delme.txt', 'r')
> sStr = oFile.readline()
> while (sStr):
>    # do something with sStr
>    sStr = oFile.readline ()
> oFile.close()

is that microsoft python? ;-)

fwiw, the standard pydiom (at least as long
as we're talking 1.5.2) is:

    f = open('delme.txt') # rt is default
    while 1:
        s = f.readline()
        if not s:
            break
        # do something

> Someone please correct me if this does not have the reduced memory
> requirements for large files that I believe it does.

for a better speed/memory tradeoff, you
can use "readlines" in the following way:

    f = open('delme.txt')
    while 1:
        lines = f.readlines(100000)
        if not lines:
            break
        for s in lines:
            # do something

also see the fileinput module.

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->

    "Get into a rut early: Do the same processes the
    same way. Accumulate idioms. Standardize. The
    only difference between Shakespeare and you
    was the size of his idiom list - not the size of his
    vocabulary." -- Alan Perlis





More information about the Python-list mailing list