使用制表设置表格

时间:2015-11-10 19:38:43

标签: python file

我有一个表单

中的几个人的txt文件
[Name1, age1, height1]
[Name2, age2, height2]
etc.

我想读取文件并将行附加到表格。

f = open('my_file.txt','r')
table=[]
for line in f:
table.append(line)

a = tabulate(table,headers=["name","age","height"])

这不起作用。我相信问题是,在我追加所有行后,我得到了

table = ["[Name1, age1, height1]\n", "[Name2, age2, height2]\n", etc.], 

虽然我希望它是

table = [[Name1, age1, height1], [Name2, age2, height2], etc.]

2 个答案:

答案 0 :(得分:1)

您可以简单地遍历文件对象并在列表解析中使用ast.literal_eval将您的行转换为列表对象:

from ast import literal_eval
with open('my_file.txt','r') as f:
     table = [literal_eval(line) for line in f]

请注意,由于使用literal_eval可能会为SyntaxError等无效行格式引发ValueErrorName1, age1, height1],因此您可以使用try_except来处理此类情况:

with open('my_file.txt','r') as f:
     table = []       
     for line in f:
        try:
            table.append[literal_eval(line)]
        except (SyntaxError,ValueError):
            # do stuff  

另请注意,作为处理文件对象的更加pythonic方式,最好使用with语句,该语句将在块结束时自动关闭文件。

答案 1 :(得分:1)

>>> table = [line.rstrip('\n')[1:-1].split(',') for line in open('file')]
>>> table
[['Name1', ' age1', ' height1'], ['Name2', ' age2', ' height2']]