Reputation: 791
I have a txt file for several people in a form
[Name1, age1, height1]
[Name2, age2, height2]
etc.
I want to read the file and append line to a table.
f = open('my_file.txt','r')
table=[]
for line in f:
table.append(line)
a = tabulate(table,headers=["name","age","height"])
That doesn't work. I believe the problem is that after I append all the lines I get
table = ["[Name1, age1, height1]\n", "[Name2, age2, height2]\n", etc.],
while I want it to be
table = [[Name1, age1, height1], [Name2, age2, height2], etc.]
Upvotes: 1
Views: 550
Reputation: 107287
You can simply loop over the file object and use ast.literal_eval
within a list comprehension to convert your lines to list objects :
from ast import literal_eval
with open('my_file.txt','r') as f:
table = [literal_eval(line) for line in f]
Note that since using literal_eval
may raise SyntaxError
or ValueError
for invalid line formats like Name1, age1, height1]
you can use a try_except to handle such cases:
with open('my_file.txt','r') as f:
table = []
for line in f:
try:
table.append[literal_eval(line)]
except (SyntaxError,ValueError):
# do stuff
Also note that as a more pythonic way for dealing with file objects you better to use with
statement which will close the file automatically at the end of the block.
Upvotes: 1
Reputation: 5194
>>> table = [line.rstrip('\n')[1:-1].split(',') for line in open('file')]
>>> table
[['Name1', ' age1', ' height1'], ['Name2', ' age2', ' height2']]
Upvotes: 1