从文本文件中读取特定行并使用 Python 分配给变量 2.7

Read specific line from text file and assign to variable using Python 2.7

我想在一个文本文件中自动搜索 3 行文本,然后将其指定为 python 脚本中的变量。该过程基本上包括 tkinter 提示用户 select 文本文件,然后三行位于文本文件中并分配为变量。所需的三行文本将始终位于文本文件中的相同位置(例如,它始终是第 10、11 和 12 行)。下面是我能够做的,但是这只会打印整个文本文件。

#set bounds
bounds=tkFileDialog.askopenfile(title='Select bounds text file:',filetypes=[("Text files","*.txt")])

rbounds=bounds.readlines()
for line in rbounds:
    print line

最后的打印语句是为了看运行脚本后的结果是什么。 如何拆分或切片文本文件中的行,然后将其分配给变量?

您可以使用切片语法来获取子列表。请记住,列表在 Python.

中是 0 索引的
rbounds = bounds.readlines()
lines_with_data = rbounds[9:12]    # gives lines 9-11, given first line is 0th
for l in lines_with_data:
    pass  # parse_line here