【问题标题】:python write() function automatically creates newline in filepython write() 函数自动在文件中创建换行符
【发布时间】:2020-04-01 22:18:12
【问题描述】:

我正在使用 write() 将数组打印到将由另一个脚本读取的文件,如下所示:

file2write=open("arrays.txt",'w')
file2write.write(str(array1)+'\n')
file2write.write(str(array2))
file2write.close()

我希望每个仅占一行的数组可以被另一个脚本读取,但是当数组变大时我会得到这个:

1 [ 0.   0.   0.  -0.4  0.6  0.   0.   0.   0.  -0.4  0.6 -0.4  0.6  0.2
2   0. ]
3 [0.1 0.3 0.3 0.1 0.1 0.5 0.5 0.7 0.7 0.3 0.3 0.5 0.5 0.7 0.7]

如何得到这个,尽管数组的大小:

1 [ 0.   0.   0.  -0.4  0.6  0.   0.   0.   0.  -0.4  0.6 -0.4  0.6  0.2   0. ]
2 [0.1 0.3 0.3 0.1 0.1 0.5 0.5 0.7 0.7 0.3 0.3 0.5 0.5 0.7 0.7]

【问题讨论】:

  • 你确定文件中有一个实际的换行符吗?许多文本编辑器会换行很长的行,因此它看起来可能跨越多行,但实际上只占一行。您能否尝试在您用于查看文件的编辑器中找到换行功能并将其关闭,然后重新检查您的输出?
  • Python write() 除了你给它的东西之外不会写任何东西。它不会自己添加换行符。
  • 不,它是在一定大小后分割线。从脚本中读取时出现此错误。语法错误:解析时出现意外 EOF .... xblocos = literal_eval(x) .... in literal_eval node_or_string = parse(node_or_string, mode='eval') 文件“”,第 1 行 [0.,0., 0.,-0.4,0.6,0.,0.,0.,0.,-0.4,0.6,-0.4,0.6,0.2 ^
  • 这是一个 numpy 数组,我从文件中读取它是这样的: coords = open("coordenadas_blocos.txt", "r") coords = coords.readlines() x = coords[0] y = coords[1] x = re.sub("\n", "", x) x = re.sub("\s+", ",", x) x = x.replace("[,", "[") xblocos = literal_eval(x) ... y 也是一样

标签: python numpy newline


【解决方案1】:

str(array1) 正在将 numpy 数组拆分为多行。

避免这种情况的一种方法是使用str(list(array1))

另一种方法是使用numpy.array2string(array1, max_line_width=1000),或者任何合理的线宽。

【讨论】:

  • 是的,我现在才自己发现!似乎 numpy 默认打印固定宽度为 70 个字符的数组。使用 list(array) 解决了这个问题。谢谢=)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 2017-04-16
  • 2021-11-20
相关资源
最近更新 更多