Đọc và ghi file nhị phân trong python
đọc và ghi file nhị phân trong python
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
import random
import operator
# create random bytes
def randomBytes(size):
bytes = []
for x in range(size):
bytes.append(random.randrange(0, 255))
return bytes
def displayBytes(bytes):
print('-' * 20)
for index, item in enumerate(bytes, start = 1):
print(f'{index} = {item} ({hex(item)})')
print('-' * 20)
#write bytes
def writeBytes(filename, bytes):
with open(filename, 'wb') as file:
for i in bytes:
file.write(i.to_bytes(1, byteorder='big'))
#read bytes
def readBytes(filename):
bytes = []
with open(filename, 'rb') as file:
while True:
b = file.read(1)
if not b:
break
bytes.append(int.from_bytes(b, byteorder='big'))
return bytes
#create the random bytes.
outbytes = randomBytes(10)
displayBytes(outbytes)
#write bytes
filename = 'test.txt'
writeBytes(filename, outbytes)
#read bytes
inbytes = readBytes(filename)
displayBytes(inbytes)
print(f'Match: {operator.eq(outbytes, inbytes)}')
Link tham khảo
Tài liệu tham khảo
Machine learning cơ bản
Hết.