Populating a list

Tim Hammerquist tim at vegeta.ath.cx
Sun Dec 16 10:42:57 EST 2001


mlorfeld <matt at lorfeld.com> graced us by uttering:
> I am new to python (about 72 hours into learning), and am having
> problems with reading a file (sate abbreviations) with one item per
> line and populating each line into a list.  The problem is that each
> item ends with \012 after each state ie WI\012.

This is intended and it's explained in the Python Library Reference.

The following is from the documentation on built-in file objects:
< http://www.python.org/doc/current/lib/bltin-file-objects.html >

    A trailing newline character is kept in the string (footnote 2.7)
    (but may be absent when a file ends with an incomplete line).

  Footnote 2.7
    The advantage of leaving the newline on is that an empty string
    can be returned to mean EOF without being ambiguous. Another
    advantage is that ... you can tell whether the last line of a
    file ended in a newline or not...

> Here is the code that I am using:
> 
> f=open('/home/mlorfeld/states.txt', 'r+')

'r+' mode not necessary as you're only reading the file. 'r' is
sufficient and is the default.

> states=f.readlines()#populates a list from file

> f.close

f.close is a method, but to call it you must use:

  f.close()

> print states

As long as your script will be staying on operating systems whose line
separators (eg, '\012') is only one byte, try the following.

    # classic Python
    f = open('/home/mlorfeld/states.txt')
    states = []
    for line in f.readlines():
        states.append(line[:-1])
    f.close()
    print states

    # Python >= 2.2
    f = open('/home/mlorfeld/states.txt')
    states = [ line[:-1] for line in f ]
    f.close()
    print states

HTH
Tim Hammerquist
-- 
Love belongs to Desire, and Desire is always cruel.
    -- Old Man, The Sandman



More information about the Python-list mailing list