我想逐字节读取文件,并检查是否设置了每个字节的最后一位:
#!/usr/bin/python
def main():
fh = open('/tmp/test.txt', 'rb')
try:
byte = fh.read(1)
while byte != "":
if (int(byte,16) & 0x01) is 0x01:
print 1
else:
print 0
byte = fh.read(1)
finally:
fh.close
fh.close()
if __name__ == "__main__":
main()
我得到的错误是:
Traceback (most recent call last):
File "./mini_01.py", line 21, in <module>
main()
File "./mini_01.py", line 10, in main
if (int(byte,16) & 0x01) is 0x01:
ValueError: invalid literal for int() with base 16: '\xaf'
有谁有主意吗?我没有成功地使用struct和binascii模块。
发布于 2010-10-15 22:27:44
您希望使用ord
而不是int
if (ord(byte) & 0x01) == 0x01:
发布于 2010-10-16 03:22:23
一种方法:
import array
filebytes= array.array('B')
filebytes.fromfile(open("/tmp/test.txt", "rb"))
if all(i & 1 for i in filebytes):
# all file bytes are odd
另一种方式:
fobj= open("/tmp/test.txt", "rb")
try:
import functools
except ImportError:
bytereader= lambda: fobj.read(1)
else:
bytereader= functools.partial(fobj.read, 1)
if all(ord(byte) & 1 for byte in iter(bytereader, '')):
# all bytes are odd
fobj.close()
https://stackoverflow.com/questions/3943149
复制相似问题