读取所有文件名和文件中的浮点数,按浮点数排序列出它们
我的目录中有 pdb 文件,每个文件中都有一行写着“TOTAL_ENERGY: somenumber”。我想提取这些能量值和文件名,并创建一个文本文件,列出按能量值排序的它们。当我在不同的计算机上运行它时,我会遇到不同的错误,现在我很困惑。如果有人能告诉我如何正确地写它,那就太好了。
能量值是这样写的:
TOTAL_ENERGY: -94.45499999999998
到目前为止我的代码是这样的。
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!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为应该是 cols[1].strip() 而不是 cols[1][:-1] 因为 split 方法会按空格分割,结果为 ["TOTAL_ENERGY:", "-94.45499999999998"]
另外,您可能需要在末尾添加text_file.close() 确保您的文件按应有的方式关闭。
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.