【问题标题】:Write long strings to a file without line breaks in python在python中将长字符串写入没有换行符的文件
【发布时间】:2020-02-09 09:10:45
【问题描述】:

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


    【解决方案1】:

    也许这一切都是为了为 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]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-18
      • 2012-07-09
      • 2021-02-08
      • 1970-01-01
      • 2011-01-30
      • 2010-11-11
      • 1970-01-01
      • 2019-03-01
      相关资源
      最近更新 更多