从文件中特定行的列表中获取数据 (python)

Getting data from a list on a specific line in a file (python)

我有一个非常大的文件,其格式如下:

  1. [['1', '2', '3', '4']['11', '12', '13', '14']]
  2. [['5', '6', '7', '8']['55', '66', '77', '88']]

(数字表示行号)

每一行的列表都很长,不像这个例子。

现在,如果只有 1 个列表,我可以通过以下方式获取“11”值:

itemdatatxt = open("tempoutput", "r")
itemdata = eval(itemdatatxt.read())
print itemdata[1][0]

但是因为文件的每一行都包含一个新列表,所以我看不到如何获取“55”值。

我以为 itemdatatxt.readline(1) 会 select 文件的第二行,但在阅读了有关 .readline 的信息后,我明白这会导致第一行出现第二个符号。

任何人都可以向我解释如何执行此操作吗? (最好我不想更改 'tempoutput' 数据文件格式)

试试这个:

import ast
with open("tempoutput", "r") as f:
    for i, line in enumerate(f):
        if i == 1:
            itemdata = ast.literal_eval(line)
            print itemdata[1][0]
            break

enumerate(f) returns:

0, <<first line>>
1, <<second line>>
...

所以当 i 变为 1 时,我们到达第二行并输出 55​​。我们也打破循环,因为我们不关心读取其余行。

我使用 ast.literal_eval 因为它是一种更安全的评估形式。

readline() 一直读到下一个换行符。如果你第二次调用它,它将从它停止的地方读取到之后的换行符。因此,你可以有一个循环:

lines = []
with open('filepath', 'r') as f:
    lines.append(eval(f.readline()))
print lines # [[['1', '2', '3', '4'],['11', '12', '13', '14']],
            #  [['5', '6', '7', '8'],['55', '66', '77', '88']]]

或者您可以读取整个文件并按换行符拆分:

lines = open('filepath', 'r').read().split('\n');

或者,如果您想读取特定行,您可以使用 linecache 模块:

import linecache

line = linecache.getline('filepath', 2) # 2 is the second line of the file

您可以将整个文件添加到字典中,其中键是行号,值是内容(两个列表)。这样您就可以通过首先选择行号,然后选择列表,然后选择索引来轻松获得您想要的任何值。

data.txt

[['1', '2', '3', '4'], ['11', '12', '13', '14']]
[['5', '6', '7', '8'], ['55', '66', '77', '88']]
[['5', '6', '3', '8'], ['155', '66', '277', '88']]

代码

import ast

data = {}
with open('data.txt', 'r') as f:
  for indx, ln in enumerate(f):
    data[indx] = ast.literal_eval(ln.strip())

print data[1][1][0] #55
print data[1][1][3] #88