I am having trouble printing long strings to a file using Python. Specifically, I use the following code to output coords
, which is a numpy array (10 by 2).
with open('MD_traj.yml', 'a+', newline='') as outfile:
outfile.write('# Output data of MD simulation\n')
outfile.write('x-coordinates: ' + str(coords[:, 0]) + '\n')
outfile.write('y-coordinates: ' + str(coords[:, 1]) + '\n')
What I want in the output file is:
x-coordinates: [ 1.31142392 -1.10193486 -0.66411767 -0.98806056 -0.38443227 -0.99041216 0.99185667 -0.20955044 -0.17442841 1.43698767]
y-coordinates: [-1.2635609 0.50664106 1.0458195 -1.16822174 0.46595609 1.1952824 -0.87070535 0.4427565 -0.79005599 0.74077841]
However, in my output file, the lines were broken into two parts, which made parsing the file harder. As shown below.
x-coordinates: [ 1.31142392 -1.10193486 -0.66411767 -0.98806056 -0.38443227 -0.99041216
0.99185667 -0.20955044 -0.17442841 1.43698767]
y-coordinates: [-1.2635609 0.50664106 1.0458195 -1.16822174 0.46595609 1.19528241
-0.87070535 0.4427565 -0.79005599 0.74077841]
Could anyone please provide suggestions on this? I've spent a lot of time searching for solutions but there was no luck. Thank you so much in advance!
Perhaps it’s all about implementing __str__
for NumPy.
Here is my code. It solves your problem. Just use the method tolist()
from NumPy's object coords
.
import numpy as np
from random import random
x = [random() for _ in range(10)]
y = [random() for _ in range(10)]
coords = np.vstack([x, y])
with open('data.yml', 'a+', newline='') as outfile:
coords_list = coords.tolist()
outfile.write('# Output data of MD simulation\n')
outfile.write('x-coordinates: ' + str(coords_list[0]) + '\n')
outfile.write('y-coordinates: ' + str(coords_list[1]) + '\n')
Result
# Output data of MD simulation
x-coordinates: [0.8686902412164521, 0.478781961466336, 0.6641005825531633, 0.39111314403044306, 0.9438645478501313, 0.8371483392442387, 0.675984748690976, 0.7254844588305968, 0.7879460984009438, 0.7033985196947845]
y-coordinates: [0.8587330241195635, 0.4748353213357631, 0.20692421648029558, 0.8039948888725431, 0.9731648049162153, 0.7237063173464939, 0.8089361624221216, 0.16435387677097268, 0.944345230621302, 0.2901067965594649]