简体   繁体   English

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

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

I want to automatically search for 3 lines of text in a text file and then assign it as variables in a python script. 我想自动在文本文件中搜索3行文本,然后在python脚本中将其分配为变量。 The process basically consist of tkinter promting the user to select the text file and then the three lines are located in the text file and assigned as variables. 该过程主要包括tkinter提示用户选择文本文件,然后三行位于文本文件中并分配为变量。 The three lines of text required will always be in the same location in the text file (eg. it will always be lines 10, 11 and 12). 所需的三行文本将始终在文本文件中的同一位置(例如,始终为第10、11和12行)。 Below is what I was able to do, however this only prints the whole text file. 下面是我能够执行的操作,但是这只会打印整个文本文件。

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

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

The print statement at the end is to see what the results are after running the script. 最后的打印语句是查看运行脚本后的结果。 How do I go about splitting or slicing the lines in the text file and then assigning it to variables? 如何拆分或切片文本文件中的行,然后将其分配给变量?

You may use slice syntax to get sublist. 您可以使用切片语法获取子列表。 Remember that lists are 0-indexed in Python. 请记住,列表在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM