Skip to content

Commit 63804b4

Browse files
committed
Refactoring. Using black code style
1 parent b6f82cc commit 63804b4

File tree

6 files changed

+88
-85
lines changed

6 files changed

+88
-85
lines changed
Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
import struct
88

99

10-
msg = struct.pack('>I12s', 12, b'Hello World!')
10+
msg = struct.pack(">I12s", 12, b"Hello World!")
1111
print(msg) # b'\x00\x00\x00\x0cHello World!'
1212
print()
1313

14-
data = struct.unpack('>I12s', msg)
14+
data = struct.unpack(">I12s", msg)
1515
print(data) # (12, b'Hello World!')
1616

17-
data = struct.unpack('>I12s', b'\x00\x00\x00\x0cHello World!')
17+
data = struct.unpack(">I12s", b"\x00\x00\x00\x0cHello World!")
1818
print(data) # (12, b'Hello World!')
19-
Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: https://ru.wikipedia.org/wiki/BMP
@@ -14,41 +14,40 @@
1414

1515
# https://en.wikipedia.org/wiki/BMP_file_format#DIB_header_(bitmap_information_header)
1616
SIZE_BY_HEADER_TYPE = {
17-
12: 'BITMAPCOREHEADER / OS21XBITMAPHEADER',
18-
64: 'OS22XBITMAPHEADER',
19-
16: 'OS22XBITMAPHEADER',
20-
40: 'BITMAPINFOHEADER',
21-
52: 'BITMAPV2INFOHEADER',
22-
56: 'BITMAPV3INFOHEADER',
23-
108: 'BITMAPV4HEADER',
24-
124: 'BITMAPV5HEADER',
17+
12: "BITMAPCOREHEADER / OS21XBITMAPHEADER",
18+
64: "OS22XBITMAPHEADER",
19+
16: "OS22XBITMAPHEADER",
20+
40: "BITMAPINFOHEADER",
21+
52: "BITMAPV2INFOHEADER",
22+
56: "BITMAPV3INFOHEADER",
23+
108: "BITMAPV4HEADER",
24+
124: "BITMAPV5HEADER",
2525
}
2626

2727

2828
def print_info(file_name: str):
29-
with open(file_name, 'rb') as f:
29+
with open(file_name, "rb") as f:
3030
# Bitmap file header
3131
# BITMAPFILEHEADER
3232
bfType = f.read(2)
33-
print('bfType:', bfType)
33+
print("bfType:", bfType)
3434

3535
data = f.read(12)
36-
bfSize, bfReserved1, bfReserved2, bfOffBits \
37-
= struct.unpack('<IHHI', data)
38-
print('bfSize:', bfSize)
39-
print('bfReserved1:', bfReserved1)
40-
print('bfReserved2:', bfReserved2)
41-
print('bfOffBits:', bfOffBits)
36+
bfSize, bfReserved1, bfReserved2, bfOffBits = struct.unpack("<IHHI", data)
37+
print("bfSize:", bfSize)
38+
print("bfReserved1:", bfReserved1)
39+
print("bfReserved2:", bfReserved2)
40+
print("bfOffBits:", bfOffBits)
4241

4342
# DIB header
4443
data = f.read(4)
45-
size = struct.unpack('<I', data)[0]
46-
print('size:', size)
47-
print('Header:', SIZE_BY_HEADER_TYPE.get(size, '<Unknown>'))
44+
size = struct.unpack("<I", data)[0]
45+
print("size:", size)
46+
print("Header:", SIZE_BY_HEADER_TYPE.get(size, "<Unknown>"))
4847

4948

50-
if __name__ == '__main__':
51-
for file_name in glob.glob('*.bmp'):
49+
if __name__ == "__main__":
50+
for file_name in glob.glob("*.bmp"):
5251
print(file_name)
5352
print_info(file_name)
5453
print()
Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: http://vip.sugovica.hu/Sardi/kepnezo/JPEG%20File%20Layout%20and%20Format.htm
@@ -15,14 +15,14 @@
1515
def print_info(file_name: str):
1616
print(file_name)
1717

18-
with open(file_name, 'rb') as f:
18+
with open(file_name, "rb") as f:
1919
# JFIF APP0
2020

2121
# Read SOI
2222
data = f.read(2)
2323

24-
if data != b'\xff\xd8':
25-
print('Not valid JPEG!')
24+
if data != b"\xff\xd8":
25+
print("Not valid JPEG!")
2626
return
2727

2828
# APP0 marker FF E0
@@ -37,37 +37,37 @@ def print_info(file_name: str):
3737
# Find 0xff, 0xc0 to identify SOF0 marker
3838
while data:
3939
data = f.read(1)
40-
if data == b'\xff' and f.read(1) == b'\xc0':
40+
if data == b"\xff" and f.read(1) == b"\xc0":
4141
break
4242

4343
# This value equals to 8 + components*3 value
44-
length, = struct.unpack('>H', f.read(2))
44+
(length,) = struct.unpack(">H", f.read(2))
4545
# print('Length:', length)
4646

4747
# This is in bits/sample, usually 8 (12 and 16 not supported by most software).
48-
data_precision, = struct.unpack('>b', f.read(1))
48+
(data_precision,) = struct.unpack(">b", f.read(1))
4949
# print('Data precision:', data_precision)
5050

51-
height, width = struct.unpack('>HH', f.read(4))
52-
print(f' Size: {width}x{height}')
51+
height, width = struct.unpack(">HH", f.read(4))
52+
print(f" Size: {width}x{height}")
5353

5454
# Usually 1 = grey scaled, 3 = color YcbCr or YIQ 4 = color CMYK
55-
number_of_components, = struct.unpack('>b', f.read(1))
55+
(number_of_components,) = struct.unpack(">b", f.read(1))
5656
# print('Number of components:', number_of_components)
5757

5858
# Each component:
5959
# component Id(1byte): (1 = Y, 2 = Cb, 3 = Cr, 4 = I, 5 = Q)
6060
# sampling factors (1byte) (bit 0-3 vertical., 4-7 horizontal.)
6161
# quantization table number (1 byte)
62-
component_id, \
63-
sampling_factors, \
64-
quantization_table_number = struct.unpack('>bbb', f.read(3))
62+
component_id, sampling_factors, quantization_table_number = struct.unpack(
63+
">bbb", f.read(3)
64+
)
6565
# print('Component id:', component_id)
6666
# print('Sampling factors:', sampling_factors)
6767
# print('Quantization table number:', quantization_table_number)
6868

6969

70-
if __name__ == '__main__':
71-
for file_name in glob.glob('*.jpg') + glob.glob('*.jpeg'):
70+
if __name__ == "__main__":
71+
for file_name in glob.glob("*.jpg") + glob.glob("*.jpeg"):
7272
print_info(file_name)
7373
print()

struct__examples__parse_binary_files/read_PNG_header/main.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html
@@ -10,7 +10,6 @@
1010

1111
import glob
1212
import struct
13-
1413
import zlib
1514

1615

@@ -22,19 +21,19 @@ def print_info(file_name: str):
2221
print(file_name)
2322

2423
def read_chunk(f) -> (int, bytes, bytes, int):
25-
chunk_length, = struct.unpack('>I', f.read(4))
24+
(chunk_length,) = struct.unpack(">I", f.read(4))
2625
chunk_type = f.read(4)
2726
chunk_data = f.read(chunk_length)
28-
chunk_CRC, = struct.unpack('>I', f.read(4))
27+
(chunk_CRC,) = struct.unpack(">I", f.read(4))
2928

3029
return chunk_length, chunk_type, chunk_data, chunk_CRC
3130

32-
with open(file_name, 'rb') as f:
31+
with open(file_name, "rb") as f:
3332
# HEADER
3433
data = f.read(8)
3534

36-
if data != b'\x89PNG\r\n\x1a\n':
37-
print('Not valid PNG!')
35+
if data != b"\x89PNG\r\n\x1a\n":
36+
print("Not valid PNG!")
3837
return
3938

4039
# After the header comes a series of chunks, each of which conveys certain information about the image.
@@ -56,17 +55,19 @@ def read_chunk(f) -> (int, bytes, bytes, int):
5655
# Check CRC
5756
assert crc32_from_bytes(chunk_type + chunk_data) == chunk_CRC
5857

59-
width, \
60-
height, \
61-
bit_depth, \
62-
color_type, \
63-
compression_method, \
64-
filter_method, \
65-
interlace_method = struct.unpack('>IIbbbbb', chunk_data)
66-
print(f' Size: {width}x{height}')
58+
(
59+
width,
60+
height,
61+
bit_depth,
62+
color_type,
63+
compression_method,
64+
filter_method,
65+
interlace_method,
66+
) = struct.unpack(">IIbbbbb", chunk_data)
67+
print(f" Size: {width}x{height}")
6768

6869

69-
if __name__ == '__main__':
70-
for file_name in glob.glob('*.png'):
70+
if __name__ == "__main__":
71+
for file_name in glob.glob("*.png"):
7172
print_info(file_name)
7273
print()
Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: https://en.wikipedia.org/wiki/List_of_file_signatures
@@ -12,24 +12,25 @@
1212

1313

1414
def is_id3(data: bytes) -> bool:
15-
return data[:3] == b'ID3'
15+
return data[:3] == b"ID3"
1616

1717

1818
def is_mp3(data: bytes) -> bool:
1919
if is_id3(data):
2020
return True
2121

2222
first_2 = data[:2]
23-
for signature in [b'\xFF\xFB', b'\xFF\xF3', b'\xFF\xF2']:
23+
for signature in [b"\xFF\xFB", b"\xFF\xF3", b"\xFF\xF2"]:
2424
if first_2 == signature:
2525
return True
2626

2727
return False
2828

2929

30-
if __name__ == '__main__':
30+
if __name__ == "__main__":
3131
# SimplePyScripts\
3232
from pathlib import Path
33+
3334
ROOT_DIR = Path(__file__).resolve().parent.parent.parent
3435

3536
for file_name in ROOT_DIR.rglob("*.mp3"):
@@ -38,20 +39,24 @@ def is_mp3(data: bytes) -> bool:
3839
data = file_name.read_bytes()
3940
_is_mp3 = is_mp3(data)
4041
_is_id3 = is_id3(data)
41-
print(f' IS MP3: {_is_mp3}')
42-
print(f' IS ID3: {_is_id3}')
42+
print(f" IS MP3: {_is_mp3}")
43+
print(f" IS ID3: {_is_id3}")
4344
if _is_id3:
4445
header = data[:10]
4546

4647
# 3b 2b 1b 4b
47-
file_id, version, flags, size = struct.unpack('<3sHB4s', header)
48-
real_size = int("".join(map(lambda x: bin(x)[2:].zfill(8), size)).replace('0', ''), 2)
49-
50-
print(f' ID3.header: {"".join(map(lambda x: hex(x)[2:].zfill(2), header))}')
51-
print(f' ID3.file_id: {file_id}')
52-
print(f' ID3.version: {version}')
53-
print(f' ID3.flags: {bin(flags)[2:].zfill(8)}')
48+
file_id, version, flags, size = struct.unpack("<3sHB4s", header)
49+
real_size = int(
50+
"".join(map(lambda x: bin(x)[2:].zfill(8), size)).replace("0", ""), 2
51+
)
52+
53+
print(
54+
f' ID3.header: {"".join(map(lambda x: hex(x)[2:].zfill(2), header))}'
55+
)
56+
print(f" ID3.file_id: {file_id}")
57+
print(f" ID3.version: {version}")
58+
print(f" ID3.flags: {bin(flags)[2:].zfill(8)}")
5459
print(f' ID3.size: {" ".join(map(lambda x: hex(x)[2:].zfill(2), size))}')
55-
print(f' ID3.real_size: {real_size} bytes')
60+
print(f" ID3.real_size: {real_size} bytes")
5661

5762
print()
Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,38 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33

4-
__author__ = 'ipetrash'
4+
__author__ = "ipetrash"
55

66

77
# SOURCE: https://pep8.ru/doc/tutorial-3.1/11.html
88

99

1010
import struct
1111

12+
# pip install tabulate
13+
from tabulate import tabulate
1214

13-
with open('myfile.zip', 'rb') as f:
15+
16+
with open("myfile.zip", "rb") as f:
1417
rows = []
15-
headers = ('file_name', 'crc32', 'comp_size', 'uncomp_size')
18+
headers = ("file_name", "crc32", "comp_size", "uncomp_size")
1619

1720
data = f.read()
1821
start = 0
1922

2023
# Показать первые три заголовка
2124
for _ in range(3):
2225
start += 14
23-
fields = struct.unpack('<IIIHH', data[start:start + 16])
26+
fields = struct.unpack("<IIIHH", data[start : start + 16])
2427
crc32, comp_size, uncomp_size, file_name_size, extra_size = fields
2528

2629
start += 16
27-
file_name = data[start:start + file_name_size]
28-
file_name = str(file_name, 'utf-8')
30+
file_name = data[start : start + file_name_size]
31+
file_name = str(file_name, "utf-8")
2932
start += file_name_size
3033

3134
print(
32-
f'file_name: {file_name}, crc32: {hex(crc32)}, comp_size: {comp_size}, uncomp_size: {uncomp_size}'
35+
f"file_name: {file_name}, crc32: {hex(crc32)}, comp_size: {comp_size}, uncomp_size: {uncomp_size}"
3336
)
3437
rows.append((file_name, hex(crc32), comp_size, uncomp_size))
3538

@@ -38,7 +41,7 @@
3841

3942
print()
4043

41-
# RESULT:
44+
print(tabulate(rows, headers, tablefmt="grid"))
4245
# +-------------+------------+-------------+---------------+
4346
# | file_name | crc32 | comp_size | uncomp_size |
4447
# +=============+============+=============+===============+
@@ -48,7 +51,3 @@
4851
# +-------------+------------+-------------+---------------+
4952
# | result.csv | 0xefede9b1 | 8 | 6 |
5053
# +-------------+------------+-------------+---------------+
51-
52-
# pip install tabulate
53-
from tabulate import tabulate
54-
print(tabulate(rows, headers, tablefmt="grid"))

0 commit comments

Comments
 (0)