-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC1_binary_reader.py
More file actions
49 lines (33 loc) · 1.14 KB
/
C1_binary_reader.py
File metadata and controls
49 lines (33 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
C1: Binary File Structure Reader
Reads structured binary records and allows appending new records.
"""
import struct
FILE_NAME = "records.bin"
RECORD_FORMAT = "i20sd"
RECORD_SIZE = struct.calcsize(RECORD_FORMAT)
def read_records():
try:
with open(FILE_NAME, "rb") as f:
while True:
chunk = f.read(RECORD_SIZE)
if not chunk:
break
record_id, name, value = struct.unpack(RECORD_FORMAT, chunk)
name = name.decode("utf-8").rstrip("\x00")
print(f"ID: {record_id}, Name: {name}, Value: {value}")
except FileNotFoundError:
print("Binary file not found yet.")
def append_record():
record_id = int(input("Enter ID: "))
name = input("Enter name: ")
value = float(input("Enter value: "))
name_bytes = name.encode("utf-8")
name_bytes = name_bytes.ljust(20, b"\x00")
with open(FILE_NAME, "ab") as f:
f.write(struct.pack(RECORD_FORMAT, record_id, name_bytes, value))
if __name__ == "__main__":
print("Existing Records:")
read_records()
print("\nAdd New Record")
append_record()