简体   繁体   中英

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. 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. 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). 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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