-1

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

4

3 回答 3

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

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

于 2012-04-25T08:00:49.727 回答
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()over file(),文档明确指出:

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

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

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

于 2012-04-25T07:44:25.470 回答
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)
于 2012-04-25T07:32:17.363 回答