bit2bin: close input file explicitly

This commit is contained in:
Sebastien Bourdeauducq 2016-05-21 21:50:08 +08:00
parent 65c835e991
commit 852ddb7796
1 changed files with 29 additions and 30 deletions

View File

@ -32,39 +32,38 @@ def flip32(data):
def bit2bin(bit, bin, flip=False): def bit2bin(bit, bin, flip=False):
bitfile = open(bit, "rb") with open(bit, "rb") as bitfile:
l, = struct.unpack(">H", bitfile.read(2))
if l != 9:
raise ValueError("Missing <0009> header, not a bit file")
l, = struct.unpack(">H", bitfile.read(2)) bitfile.read(l)
if l != 9: d = bitfile.read(*struct.unpack(">H", bitfile.read(2)))
raise ValueError("Missing <0009> header, not a bit file") if d != b"a":
raise ValueError("Missing <a> header, not a bit file")
bitfile.read(l) d = bitfile.read(*struct.unpack(">H", bitfile.read(2)))
d = bitfile.read(*struct.unpack(">H", bitfile.read(2))) print("Design name:", d)
if d != b"a":
raise ValueError("Missing <a> header, not a bit file")
d = bitfile.read(*struct.unpack(">H", bitfile.read(2))) while True:
print("Design name:", d) key = bitfile.read(1)
if not key:
while True: break
key = bitfile.read(1) if key in b"bcd":
if not key: d = bitfile.read(*struct.unpack(">H", bitfile.read(2)))
break name = {b"b": "Partname", b"c": "Date", b"d": "Time"}[key]
if key in b"bcd": print(name, d)
d = bitfile.read(*struct.unpack(">H", bitfile.read(2))) elif key == b"e":
name = {b"b": "Partname", b"c": "Date", b"d": "Time"}[key] l, = struct.unpack(">I", bitfile.read(4))
print(name, d) print("found binary data length:", l)
elif key == b"e": d = bitfile.read(l)
l, = struct.unpack(">I", bitfile.read(4)) if flip:
print("found binary data length:", l) d = flip32(d)
d = bitfile.read(l) with open(bin, "wb") as f:
if flip: f.write(d)
d = flip32(d) else:
with open(bin, "wb") as f: d = bitfile.read(*struct.unpack(">H", bitfile.read(2)))
f.write(d) print("Unexpected key: ", key, d)
else:
d = bitfile.read(*struct.unpack(">H", bitfile.read(2)))
print("Unexpected key: ", key, d)
if __name__ == "__main__": if __name__ == "__main__":