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

时间:2015-09-16 07:12:08

标签: python python-2.7 readlines

我想在文本文件中自动搜索3行文本,然后在python脚本中将其指定为变量。该过程基本上由tkinter提示用户选择文本文件,然后三行位于文本文件中并指定为变量。所需的三行文本将始终位于文本文件中的相同位置(例如,它将始终是第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

最后的print语句是查看运行脚本后的结果。 如何分割或切片文本文件中的行,然后将其分配给变量?

1 个答案:

答案 0 :(得分:1)

您可以使用切片语法来获取子列表。请记住,列表在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
相关问题