【问题标题】:Appending to a .data file in python在 python 中附加到 .data 文件
【发布时间】:2020-02-13 08:16:10
【问题描述】:

类似于Meenakshi 我正在尝试使用 numpy 的 savetxt 函数将数据附加到文件中。

我有一个 .data 文件,我想将更多 float32 数据附加到。

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))

# save as new training results
np.savetxt(sampleData,samples)
np.savetxt(responseData,responses)

# want the option to append to previously written results 

我可以将以下内容附加为二进制文件,但我需要在 float32 中附加。

# append to old training results 
    with open(sampleData, 'ab+') as fs:
        fs.write(samples)
    with open(responseData, 'ab+') as fr:
        fr.write(responses)

当我尝试时

# append to old training results 
        with open(sampleData, 'a+') as fs:
            fs.write(samples)
        with open(responseData, 'a+') as fr:
            fr.write(responses)

我得到“TypeError:write() 参数必须是 str,而不是 numpy.ndarray”

鉴于上述情况,我应该使用什么语法/扩展名与 python 中的这种 .data 文件类型进行交互?

【问题讨论】:

  • 到目前为止你尝试过什么?它说什么属性不存在?
  • 我编辑了问题以使其更清楚:)
  • 我更新了我的答案 - 看到了关于附加的部分,我之前错过了。

标签: python file types append file-extension


【解决方案1】:

更新:

最初没有看到您对追加的评论。 answer in your linked question 表明您在正确的轨道上:

以下内容将按预期附加您的数据,但不会转储“乱码”(字节)。 np.savetxt 显然负责进行适当的格式化/编码,以便所写的内容是人类可读的。

with open(some_file, 'ab+') as fo:
    np.savetxt(fo, responses)

原始 - 留在这里解释为什么 OP 方法不起作用

您的评论暗示正在发生的事情:

以下内容确实附加,但它输入了乱码(我假设是因为二进制,但没有 b 它告诉我我需要输入一个字符串)--> with open(sampleData, 'ab+') as fs: fs. write(samples) with open(responseData, 'ab+') as fr: fr.write(responses)

当您尝试在没有b 的情况下编写时,它会适当地抱怨,因为您需要在正常写入模式下给它一个字符串 - 您不能只编写一个列表/数组(是samplesresponses 是什么)。当您使用b 时,您正在以二进制/字节模式写入,因此您传递给write 的任何内容都会被强制转换为字节。如果我以二进制模式编写以下内容,这就是我看到的:

resp = np.array([1, 2, 4, 5], np.float32)
resp = resp.reshape((resp.size, 1))
np.savetxt(file1, resp)
with open(file2, 'ab+') as fo:
    fo.write(resp)

# From Hex view of written file
00 00 80 3F 00 00 00 40 00 00 80 40 00 00 A0 40

这与在我创建的数组上调用bytes(...) 相同:

import binascii
binascii.hexlify(bytes(resp))

# produces:
b'0000803f00000040000080400000a040' -> '00 00 80 3f 00 00 00 40 00 00 80 40 00 00 a0 40'

因此,您只需要将数据格式化为str 友好的表示形式,例如加入字符串(例如):

>>> ', '.join(str(x) for x in resp)
'[1.], [2.], [4.], [5.]'

...但是如何格式化它当然取决于您的要求。

【讨论】:

    猜你喜欢
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多