3

I have a text file which looks like:


line A
line B
line C
line D

objective
8.5770822e+000
3762931e+000
0996787e+000
0070925e+000
0003053e+000
9999994e+000

line E
line F
line G

I want to import numbers under the word "objective" into a Python list.

Challenges: The number of lines (with numbers) under the line with "objective" need not be the same. It varies from file to file. I am trying to develop a generic code. So the stop condition must be based on a blank line under the numbers.

My idea: I was able to access the line "objective" with the code if line.startswith("objective") But to access the lines below until you find a blank line seems challenging.

Can you please help me with this?

Thank you very much.

2
  • 1
    What did you try? Commented Nov 17, 2020 at 12:51
  • 2
    I used the command if line.startswith("objective") to access that specific line. I can add that line to a list using list.append(line). The idea is to access all the lines under "objective", until you find a blank line. Commented Nov 17, 2020 at 12:55

2 Answers 2

3

One way to do this would be to have a flag indicating whether or not the word "objective" has been seen.

Something like this:

res = []
objective_seen = False
with open(filename) as fh:
    for line in fh:
        if objective_seen:
            if line:
                res.append(line)
            else:  # blank line
                break
        else:  # objective not yet seen
            if line.startswith('objective'):
                objective_seen = True

Another way would be to have two loops, one to process the file up to "objective", the other to process the rest:

res = []
with open(filename) as fh:
    for line in fh:
        if line.startswith('objective'):
            break
    else:
        raise ValueError('No "objective" section in file')

    for line in fh:
        if line:
            res.append(line)
        else:
            break
Sign up to request clarification or add additional context in comments.

Comments

2

Here is my proposition:

  • Read the file into a list
  • save each lines from "Objective" to the last line into a new list numbers
  • take away the 0th elements and all the elements from the first empty '' elements to the end.

What will be left are the numbers you need.

Here is my implem

def main():
    #read file 
    g = open(r"test.txt")
    # read all lines
    lst= g.readlines();
    numbers = []
    # at the beginning no number is found

    # flag to track if we shall save or not in the list
    start_saving = False
    # a loop to save all from objective to the end
    for l in lst:
       l=l.strip("\n")
       if ("objective" in l):
            start_saving= True
       if (start_saving):
            numbers.append(l)

    # here we  obtain an array containing all elements from Objective to the end
    # ['objective', '8.5770822e+000', '3762931e+000', '0996787e+000', '0070925e+000', '0003053e+000', '9999994e+000', '', 'line E', 'line F', 'line G']
    # i will now strip away all elements of index 0 ("Objective") and from the first empty index (the first line containing nothing)
    # only keep elements from 1st to the first element not empty
    numbers = numbers[1:numbers.index('')]
    print numbers
    # display : ['8.5770822e+000', '3762931e+000', '0996787e+000', '0070925e+000', '0003053e+000', '9999994e+000']

if __name__ == '__main__':
    main()

This outputs:

['8.5770822e+000', '3762931e+000', '0996787e+000', '0070925e+000', '0003053e+000', '9999994e+000']

7 Comments

Thank you for your answer. I would like to know an idea for one more case. Some lines may have more than one number, separated by a space. In that case, what modification would you make to your code?
I will look and make you a proposition. Could you provide an example of txt file and the corresponding output in order to have the same test basis
Yes, thank you. But I am not sure how to share a text file with you.
No worries, I think I understand what you want. I will look and propose it a little later this day
Thank you very much for your time and support. Here I have the format and the expected results pastebin.pl/view/5b2394e9 In fact, I simplified the text I am working with, for easy communication. I am sharing the original text as well pastebin.pl/view/668a3bee
|

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.