Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中附加到.data文件_Python_File_Types_Append_File Extension - Fatal编程技术网

在python中附加到.data文件

在python中附加到.data文件,python,file,types,append,file-extension,Python,File,Types,Append,File Extension,与此类似,我尝试使用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,res

与此类似,我尝试使用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文件类型交互?

Update: 没有看到您最初对附加的评论。显示您在正确的轨道上:

下面将按预期添加数据,但不会转储乱码字节。显然,np.savetxt负责进行适当的格式化/编码,以使编写的内容具有可读性

with open(some_file, 'ab+') as fo:
    np.savetxt(fo, responses)
原始-留下来解释OP方法不起作用的原因 您的评论暗示了正在发生的事情:

下面的代码确实追加了,但由于二进制代码的缘故,它输入了我假设的乱码,但没有b,它告诉我需要输入一个字符串->使用opensampleData,'ab+'作为fs:fs.writesamples,使用openresponseData,'ab+'作为fr:fr.writeresponses

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

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
这与调用字节相同。。。在我制作的阵列上:

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.]'

…但您如何设置格式当然取决于您的要求。

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