我有这个代码:
for ts in u.trajectory:
C= u.select_atoms("resid 1-360").center_of_geometry()
print("Frame: {0:5d}, Time: {1:8.3f} ps".format(ts.frame, u.trajectory.time))
print(C)
它正常工作,实际上我在控制台中具有正确的输出:
Frame: 1368, Time: 66.879 ps
[130.05973581 252.66481884 127.07351932]
Frame: 1369, Time: 66.928 ps
[130.06893641 252.44106886 126.9491674 ]
Frame: 1370, Time: 66.977 ps
[130.1192347 252.60012987 126.83614898]
Frame: 1371, Time: 67.026 ps
[130.18082118 252.68871264 127.0049008 ]
Frame: 1372, Time: 67.075 ps
[130.08001144 252.82253858 127.01025264]
Frame: 1373, Time: 67.124 ps
[130.08522401 252.72558336 126.90693256]
exc.. exc..
我的问题是: 如何将所有结果保存在单个txt文件中?
答案 0 :(得分:1)
这是示例代码
with open('output.txt', 'w+') as opfile:
for ts in u.trajectory:
C= u.select_atoms("resid 1-360").center_of_geometry()
opfile.write("Frame: {0:5d}, Time: {1:8.3f} ps\n".format(ts.frame, u.trajectory.time))
opfile.write(str(C)+'\n')
答案 1 :(得分:0)
您可以将所有这些数据附加到列表中,然后以这种方式将其写入文本文件。
tempList = []
for ts in u.trajectory:
C= u.select_atoms("resid 1-360").center_of_geometry()
tempList.append("Frame: {0:5d}, Time: {1:8.3f} ps".format(ts.frame, u.trajectory.time))
tempList.append(C)
f= open("sample.txt","w+")
for line in tempList:
f.write(line)
答案 2 :(得分:0)
首先,您想要将C
的所有值保存在一个数组数组中。只需:
allValues = []
for ts in u.trajectory:
C = u.select_atoms("resid 1-360").center_of_geometry()
allValues.append([C, [ts.frame], [u.trajectory.time]])
print("Frame: {0:5d}, Time: {1:8.3f} ps".format(ts.frame, u.trajectory.time))
print(C)
接下来,您可以使用以下方法将allValues
保存到文本文件中:
arrayOfItems = [",".join(str(item)) for item in allValues]
arrayOfStrings = [";".join(cell) for cell in arrayOfItems] # Convert each value to a string
file = open("save.txt","w+")
for row in allValues:
file.write(line)
要将文件的内容读回到数组中,请执行以下操作:
allValues = []
with open("save.txt") as file:
lines = file.readlines()
for line in lines:
thisLine = line.split(";")
thisInfo = [thisSection.split(",") for thisSection in thisLine]
allValues.append([float(thisCol) for thisCol in thisInfo])