将包含数字的文本文件转换为二进制格式

时间:2015-11-23 08:42:44

标签: python io binary

我有一个只接受二进制文件的python工具。作为输入,我有一个csv文件,每行包含一个数字。我只是想读取文件并从中保存二进制格式。

我使用以下代码,但最终答案已被破解。

import sys

def main(filename):
outfile = open('nums.bin','wb')
with open(filename, 'r') as f:
  outfile.write(bytes([ l.strip() for l in f.read().splitlines()]))
outfile.close()

if __name__ == "__main__":
  main(sys.argv[1])

我的输入格式如下:

102
111
54
.

读取功能如下:

with open(datafile, 'rb') as file:
    bytes_in = bytearray(file.read())
    dataset = to_dataset(bytes_in, bits_per_symbol)
.
.
.

def to_dataset(bytes, bits_per_symbol):
    if bits_per_symbol <= 8:
        return list(bytes)
    elif bits_per_symbol <= 16:
        return [bytes[i]*256 + bytes[i+1] for i in range(0,len(bytes),2)]
    elif bits_per_symbol <= 24:
        return [bytes[i]*(256*256) + bytes[i+1]*256 + bytes[i+2] for i in range(0,len(bytes),3)]
    elif bits_per_symbol <= 32:
        return [bytes[i]*(256*256*256) + bytes[i+1]*(256*256) + bytes[i+2]*256 + bytes[i+3] for i in range(0,len(bytes),4)]
    else:
        return list()

在函数to_dataset中,bits_per_symbol由用户定义,在我的例子中等于8。

我也看下面的帖子,但我无法弄清楚我的答案: How to write a list of integers to a binary file in python

1 个答案:

答案 0 :(得分:1)

尝试:

import sys
import struct
def main(filename):
  outfile = open('nums.bin','wb')
  with open(filename, 'r') as f:
        for l in f.read().splitlines():
                print struct.pack( 'i',int(l.strip()) )
                outfile.write( struct.pack( 'i', int( l.strip() )) )
  outfile.close()

if __name__ == "__main__":
  main(sys.argv[1])