[英]Reading binary file (.chn) in Python
在python中,如何读取二进制文件(这里需要读取.chn文件)并以二进制格式显示结果?
Assuming that values are separated by a space: 假设值之间用空格隔开:
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())
In Python is better to use open()
over file()
, documentation says it explicitly: 在Python中,最好使用
open()
不是file()
,文档明确指出:
When opening a file, it's preferable to use open() instead of invoking the file constructor directly.
打开文件时,最好使用open()而不是直接调用文件构造函数。
rb
mode will open the file in binary mode. rb
模式将以二进制模式打开文件。
Reference: 参考:
http://docs.python.org/library/functions.html#open http://docs.python.org/library/functions.html#open
try this: 尝试这个:
with open('myfile.chn') as f:
data=f.read()
data=[bin(ord(x)).strip('0b') for x in data]
print ''.join(data)
and if you want only the binary data it will be in the list. 如果只需要二进制数据,它将在列表中。
with open('myfile.chn') as f:
data=f.read()
data=[bin(ord(x)).strip('0b') for x in data]
print data
In data now you will have the list of binary numbers. 现在在数据中,您将看到二进制数列表。 you can take this and convert to hexadecimal number
您可以将其转换为十六进制数
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.