0

我有文本文件:

[1]AAAAAA
[2]BBBBBB
[3]CCCCCC
[4]DDDDDD
[5]
[6]
[7]
[8]111111
[9]2222222
[10]333333
[11]4444444
[12]555555
[13]6666666

如果我有第 2 行的内容,我想获得第 9 行的内容。怎么办?

4

3 回答 3

3

将整个文件作为列表读入内存并直接对其进行索引。

with open("myfile") as data:
    lines = data.readlines()
lines[8] #9th line

或者通过像对象一样迭代文件的每一行来计数到你想要的行。

with open("myfile") as data:
    for count, line in enumerate(data)
        if count == 8:
            print line
            break
于 2013-01-10T15:06:32.313 回答
1
with open('test.txt') as f:
    print [line.strip().split(']')[-1] for i,line in enumerate(f) if i in [1,8]]

出去:

['BBBBBB', '2222222']
于 2013-01-10T15:16:39.340 回答
0

你可以这样做 :

print open("file.txt", "r").readlines()[8]
于 2013-01-10T15:10:03.550 回答