0

say i have a text file which contains the following:

Bob 15 M
John 16 M
Jen 15 F

How do I put it into a list so that the list values are:

listOne = ['Bob', '15', 'M']
listTwo = ['John', '16', 'M']
listThree = ['Jen', '15', 'F']

Thanks

A.Wolf
  • 19
  • 1
  • 7

4 Answers4

4

just split it and unpack it

bob, john, jen = [a.split() for a in open(file)]
danidee
  • 9,298
  • 2
  • 35
  • 55
  • very good point. though it would be garbage collected and closed but we cant always depend on the interpreter to do that – danidee Feb 19 '16 at 12:10
  • In CPython, it would usually be immediately garbage-collected; in other Python implementation, it might stay around for a while. – Sven Marnach Feb 19 '16 at 12:33
0

Use open file and split():

with open('text.txt') as f:
    strings = f.readlines()
    data = [string.split() for string in strings]
JRazor
  • 2,707
  • 18
  • 27
0

You can apply string.split to each line in the file:

import string

with open('text.txt') as text:
    result = map(string.split, text)

With Python 3, you need to materialise the map, otherwise the file doesn't get read before it's closed:

    result = list(map(string.split, text))

However, string.split is deprecated and would only apply to str objects, not unicode. A more general solution is to create a list comprehension:

    result = [line.split() for line in text]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
-1
with open('text.txt') as file:
    lines = file.readlines()        # Creates a list of lines
    for line in lines:
        line = line.split()         # Split each line into list of "words"

This gives you a nested list which is probably sensible. If you desperately want 3 lists, use this:

evalvar = ""
count = 0
for line in lines:
    count += 1
    evalvar += "list"+str(count)+" = "+str(line)+";"
exec(evalvar)                                         # Runs the evalvar which has
                                                      # code in it.
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
Tim
  • 2,563
  • 1
  • 23
  • 31