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
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
just split it and unpack it
bob, john, jen = [a.split() for a in open(file)]
Use open file and split():
with open('text.txt') as f:
strings = f.readlines()
data = [string.split() for string in strings]
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]
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.