Pietro Delre
Pietro Delre

Reputation: 13

how can I save all the values in a single txt file?

i have this code:

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)

it works correctly, infact i have the right output in console:

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..

My question is: how can I save all the results in a single txt file?

Upvotes: 0

Views: 289

Answers (3)

mmuppidi
mmuppidi

Reputation: 101

Here is the sample code

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')

Upvotes: 1

Geza Kerecsenyi
Geza Kerecsenyi

Reputation: 1218

First, you want to save all of the values of C in an array of arrays. Simply do:

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)

Next, you can save allValues to a text file simply using:

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)

To read the contents of the file back into an array, do:

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])

Upvotes: 1

lc74
lc74

Reputation: 134

You could append all of that data into a list then write it into a text file this way.

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)

Upvotes: 0

Related Questions