How to store the contents of a file into a list?

Skip Montanaro skip at mojam.com
Sat Jan 6 15:44:45 EST 2001


    Daniel> I've been trying to do the same when reading these records from
    Daniel> a file (The file contains 2 lines : 
    Daniel> rec11,rec12,rec13
    Daniel> rec21,rec22,rec23)

    Daniel> What needs to be done to obtain the same [nested] l1 as above?

Try this:

  f = open("/tmp/recordfile")
  l1 = []
  for line in f.readlines():
    line = line.rstrip()	# remove trailing line ending
    l1.append(line.split(",")

The split at the commas maps the string "rec11,rec12,rec13" into the list
["rec11","rec12","rec13"].  That list gets appended to l1 which winds up as
a list of lists of strings instead of a list of strings.

Cheers,

-- 
Skip Montanaro (skip at mojam.com)
Support the Mojam.com Affiliates Program: http://www.mojam.com/affl/
(847)971-7098




More information about the Python-list mailing list