簡體   English   中英

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM