如何在python中将文件的内容写入列表?

时间:2015-02-06 18:39:38

标签: python python-2.7 nested-lists

我正在学习python编程并且遇到了这个问题。我查看了其他示例,它们读取文件输入并将整个事件作为单个列表或字符串link to that example但我希望每行都是是一个列表(嵌套列表)我该怎么做请帮助
文本文件是a.txt

1234 456 789 10 11 12 13

4456 585 568 2 11 13 15 

代码的输出必须像这样

[ [1234 456 789 10 11 12 13],[4456 585 568 2 11 13 15] ]

4 个答案:

答案 0 :(得分:5)

没理由readlines - 只是遍历文件。

with open('path/to/file.txt') as f:
    result = [line.split() for line in f]

如果您想要一个整体列表列表:

with open('path/to/file.txt') as f:
    result = [map(int, line.split()) for line in f]
    # [list(map(int, line.split())) for line in f] in Python3

答案 1 :(得分:2)

你可以做到

with open('a.txt') as f:
     [[i.strip()] for i in f.readlines()]

会打印

[['1234 456 789 10 11 12 13'], ['4456 585 568 2 11 13 15']]

注意 - 这是打印字符串的初始问题的答案

要完全按照您的意愿打印而不加引号,这是一个非常错误的方法

print(repr([[i.strip()] for i in f.readlines()]).replace("'",''))

将打印

[[1234 456 789 10 11 12 13], [4456 585 568 2 11 13 15]]

答案 2 :(得分:2)

lines = open('file.txt').readlines() # parse file by lines
lines = [i.strip().split(' ') for i in lines] # remove newlines, split spaces
lines = [[int(i) for i in j] for j in lines] # cast to integers

答案 3 :(得分:2)

在结果列表中看起来你想要整数,而不是字符串;如果是的话:

with open(filename) as f:
    result = [[int(x) for x in line.strip().split()] for line in f]