Putting a line from a text file into a variable, then moving to next line

Jorge Godoy jgodoy at gmail.com
Sun Oct 7 08:09:16 EDT 2007


Vernon Wenberg III wrote:

> I'm not really sure how readline() works. Is there a way to iterate
> through a file with multiple lines and then putting each line in a
> variable in a loop?

To know how something works you can always check the docs about this
specific functionality:

>>> a = open('a')
>>> help(a.readline)
Help on built-in function readline:

readline(...)
    readline([size]) -> next line from the file, as a string.
    
    Retain newline.  A non-negative size argument limits the maximum
    number of bytes to return (an incomplete line may be returned then).
    Return an empty string at EOF.

>>> help(a.readlines)
Help on built-in function readlines:

readlines(...)
    readlines([size]) -> list of strings, each a line from the file.
    
    Call readline() repeatedly and return a list of the lines so read.
    The optional size argument, if given, is an approximate bound on the
    total number of bytes in the lines returned.

>>> 


If you are creating new variables on every loop iteration you might be
interested in two things:

        - you can loop directly through the file, on a line by line basis
        - you can assign the read line to a an array





More information about the Python-list mailing list