我有几个人的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.]
您可以简单地在文件对象上循环并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
或ValueError
针对无效的行格式,例如,Name1, 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
还要注意,作为处理文件对象的更Python方式,您最好使用with
语句,该语句将在块末尾自动关闭文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句