在Python中读取二进制文件(.chn)

时间:2012-04-25 07:28:17

标签: python file-io binary

在python中,如何读取二进制文件(这里我需要读取.chn文件)并以二进制格式显示结果?

3 个答案:

答案 0 :(得分:2)

假设值以空格分隔:

with open('myfile.chn', 'rb') as f:
    data = []
    for line in f:  # a file supports direct iteration
        data.extend(hex(int(x, 2)) for x in line.split())

在Python中,最好使用open()而不是file(),文档明确说明了这一点:

  

打开文件时,最好使用open()而不是调用   文件构造函数直接。

rb模式将以二进制模式打开文件。

参考:
http://docs.python.org/library/functions.html#open

答案 1 :(得分:2)

试试这个:

    with open('myfile.chn') as f:
        data=f.read()
        data=[bin(ord(x)).strip('0b') for x in data]
        print ''.join(data)

如果您只想要二进制数据,它将在列表中。

    with open('myfile.chn') as f:
        data=f.read()
        data=[bin(ord(x)).strip('0b') for x in data]
        print data

现在,您将拥有二进制数列表。你可以把它转换成十六进制数

答案 2 :(得分:0)

with file('myfile.chn') as f:
  data = f.read()   # read all strings at once and return as a list of strings
  data = [hex(int(x, 2)) for x in data]  # convert to a list of hex strings (by interim getting the decimal value)
相关问题