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

问题描述 投票:-1回答:2

我在使用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]

有人可以为此提供建议吗?我花了很多时间寻找解决方案,但是没有运气。提前非常感谢您!

python string line-breaks
2个回答
0
投票

也许是关于为NumPy实现__str__的全部。

这是我的代码。它解决了您的问题。只需使用NumPy对象tolist()中的方法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')

结果

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

-1
投票

如果您写一个\n字符,那么这在Linux系统上应该是换行符我在使用python3的Ubuntu笔记本电脑上检查了您的示例,情况就是这样因此,示例的输出为三行,分别是标题和x,然后是y

是否是在Linux系统上运行代码并在Microsoft系统上查看代码?

Microsoft倾向于使用“ Carriage return,line feed”,将两个字符\r\n作为行尾,并且Microsoft系统上的某些编辑器或查看器被单个换行符所混淆

© www.soinside.com 2019 - 2024. All rights reserved.