0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Works perfect. Such a simple solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.