使用`struct.pack`将数据写入文件时出错 [英] Error in using `struct.pack` for writing data to file

查看:194
本文介绍了使用`struct.pack`将数据写入文件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy.ndarray数字样本,每个数字都在1到2**20之间.

I have a numpy.ndarray sample of numbers, each between 1 and 2**20.

我想将其写入二进制文件,以便每个元素由四个字节表示.

I'd like to write it into a binary file, such that each element is represented by four bytes.

但是,生成的文件大小不同于样本大小的4倍.

However, the resulting file size is different from 4 times the size of the sample.

这是我正在使用的代码:

This is the code I'm using:

        outputFile = open('testDS', 'w')
        print len(sample)
        if (outputFile is not None):
            for s in sample:
                assert(s < 2**20)
                r = struct.pack("i", s)
                assert(len(r) == 4)
                outputFile.write(r)
        outputFile.close()

我得到的输出(样本的大小)是: 1000

The output I'm getting (the size of the sample) is: 1000

但是,结果文件大小为4026字节.

However, the resulting file size is 4026 bytes.

有什么想法为什么文件大小不完全是4000字节?

Any ideas why the file size is not exactly 4000 bytes?

推荐答案

以二进制模式打开文件:

Open the file in binary mode:

outputFile = open('testDS', 'wb')

否则,文件对象可能会对二进制数据中显示的换行符进行神奇的转换,从而导致其他字符被写入文件.参见例如 https://docs.python. org/2/tutorial/inputoutput.html#reading-and-writing-files

Otherwise, the file object may do some magic translation of newline characters that show up in your binary data, resulting in additional characters being written to the file. See, for example, https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

这篇关于使用`struct.pack`将数据写入文件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆