numpy tofile 在每一行中加上单引号

numpy tofile puts single quotes in every line

我正在尝试使用 numpy 将字符串数组保存在文件中。这是我的代码:

import numpy as np


items = ["Hello World"] * 5

np.array(items).tofile('hello.txt', "\n")

它有效,但问题是输出中的每一行都有一个单引号,这使得它看起来像这样:

'Hello World'
'Hello World'
'Hello World'
'Hello World'
'Hello World'

如何让 numpy 像这样写输出?并在末尾添加一行?

Hello World
Hello World
Hello World
Hello World
Hello World

提前致谢!

您可以通过显式传递(奇怪的默认)格式字符串来解决此问题:

np.array(items).tofile('test.txt', '\n', '%s')

显然是 the documentation is, probably for illustration purposes, different from the one actually used 中的函数签名。实际签名使用关键字参数,因此能够检测是否给出了格式字符串。如果缺少,他们可能会根据数据类型选择合适的默认值(尽管我找不到相关代码)。