在 python 中将长字符串写入没有换行符的文件

Write long strings to a file without line breaks in python

我在使用 Python 将长字符串打印到文件时遇到问题。具体来说,我使用以下代码输出 coords,这是一个 numpy 数组(10 x 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')

我想要的输出文件是:

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]

但是,在我的输出文件中,行被分成两部分,这使得解析文件变得更加困难。如下图

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]

有没有人可以对此提出建议?我花了很多时间寻找解决方案,但没有运气。提前致谢!

也许这就是为 NumPy 实现 __str__

这是我的代码。它解决了你的问题。只需使用 NumPy 对象 coords.

中的方法 tolist()
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')

结果

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