Python 将文件解析为列表列表的字典:for 循环仅附加最后一行

Python parsing file into dictionary of list of lists: for loop is only appending last line

我正在尝试解析具有一致格式的文件:一个 header 和几行按间距分隔的文本。 我想在一行有一个值时开始一个新的字典键,将以下行读入列表列表,每个列表都是拆分词。 我首先尝试使用 来尝试让程序识别新标记并使用索引计数器来设置新密钥。 然后我最初使用 this 相应地拆分行。

这是我的代码目前的样子:

import sys

def openfile(file):
    frames = {}
    index = 0
    with open(file, 'r') as f:
        for line in f:
            if line.strip() == '5310':
                index +=1
            else:
                newline = line
                print newline
                frames[index] = []
                frames[index].append([newline.split()])
        print frames

openfile(sys.argv[1])

索引将正确计数并且 'print newline' 正在打印我想要的所有行,但最终打印的字典是一个嵌套列表:

{1:[['last', 'line', 'of', 'input', 'file']]}

我想要的是:

{1:[[line1],[line2] ...], 2:[[nextline], [nextline] ...], ... , key n : [[line], [line]....[lastline]]}

我也试过:

def openfile(file):
    frames = {}
    index = 0
    with open(file) as f:
         for line in f:
            if str(line.strip()) == '5310':
                index += 1
            else:
                frames[index] = []
                frames[index].append([line.split()])
    return frames

这也行不通。 这给我留下了两个问题: 1:为什么我当前的代码会打印但不会附加我想要的行? 2. 我还能做些什么来让它工作?

编辑 谢谢!我设法让它工作。 如果有人遇到类似问题,这是我的有效代码:

import sys

def openfile(file):
    frames = {}
    index = 0
    with open(file, 'r') as f:
        for line in f:
            if line.strip() == '5310':
                index +=1
                frames[index] = []
            else:
                newline = line
                print newline
                frames[index].append([newline.split()])
        print frames

openfile(sys.argv[1])

你的问题很明显......一旦你看到问题:-)

            frames[index] = []
            frames[index].append([newline.split()])

每次通过循环,您都会清除之前的进度,并从一个新的空列表开始。因此,只有最后一次迭代的结果在 frames.

初始化代码只需执行一次,在您进入循环之前。

with open(file) as f:
     frames[index] = []
     for line in f:

...或其他适用于您的应用程序的点。