'read all file names and a float in the files, list them sorted by float

I have pdb files in a directory, and in each of them there is a line written "TOTAL_ENERGY: somenumber" .i want to extract those energy values and the file names and make a text file listing them sorted by the energy values. i get different errors when i run it in different computers now im pretty confused. would be nice if someone can tell me how to write it correctly.

the energy value is written like this:

TOTAL_ENERGY: -94.45499999999998

And my code is like this so far.


import os 
import sys

#open and read each file in the path, if "TOTAL_ENERGY:" is written in a line extract 
#the total energy value, which is seperated by space, and in a txt file make a list
#of the file names and the energy value next to it. sort the list by the energy value

filename= os.listdir("/path/to/files/")
# print(file_list)
filename_and_energy=[]
text_file =  open('list_pdbs_energies.txt' , 'w')
for f in filename:
    with open(f, 'r') as text:
        lines=text.readlines()
        for l in lines:
            if 'TOTAL_ENERGY:' in l:
                cols =l.split()
                energy = float(cols[1][:-1])
                filename_and_energy.append((f, energy))
filename_and_energy.sort(key=lambda x: x[1])
text_file.write(filename_and_energy) ```



Thanks a bunch!


Solution 1:[1]

I think it should be cols[1].strip() instead of cols[1][:-1] because the split method will split by space which will result in ["TOTAL_ENERGY:", "-94.45499999999998"]

Also, you may want to add at the end text_file.close() to make sure that your file gets closed as it should be.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1