0

I have an output file with a load of information in and I want to read a number value that appears after a specific word.

In my file, I have a line such as

"Final energy, E = -82137.1098 eV"

What I would like to do is search my file for the string 'Final energy' and then read and store the number value.

So far I have managed to search the file for 'Final energy' and print the entire line containing that string but I can't seem to find a way to then read the number.

So far my code goes like this

energystring = 'Final energy'

with open(filename, 'r') as file:
    for line in file:
        if energystring in line:
            energyline = line
print(energyline)

Thank you for any help you can give.

corky
  • 3
  • 1
  • Of you're not afraid to use `regex`, you could use a suitable pattern to extract the number and then convert it to `float`. See e.g. here: https://stackoverflow.com/questions/32680030/match-text-between-two-strings-with-regular-expression – FObersteiner Nov 04 '19 at 16:40

1 Answers1

0

You just need to parse the number out of the string then. You can split the string on whitespace to get all the words, try to cast each word to a float, and get the one that works. Since there's only one number in the string, whatever successfully casts to float is your energy number.

def get_energy_level(line):
    for word in line.split():
        try:
            return float(word)
        except ValueError:
            pass


with open(filename, 'r') as file:
    for line in file:
        if energystring in line:
            energy_level = get_energy_level(line)  
Jtcruthers
  • 854
  • 1
  • 6
  • 23