Можно ли в Python создавать бинарные файлы? Конечно можно.
Для этого в Python есть следующие инструменты:
▫️ тип данных bytes и bytearray
▫️ открытие файла в режиме wb (write binary) или rb (read binary)
▫️ модуль struct
Про модуль struct поговорим в первую очередь.
Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных.
В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла.
Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла.
Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид.
Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки).
Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение.
При этом следует помнить что мы говорим о типах языка С а не Python.
Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще.
Вот какие токены формата у нас есть.
Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы.
В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты.
Запакуем в байты простое число, токен "i".
>>> import struct
>>> struct.pack('=i', 10)
b'\n\x00\x00\x00'
Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов.
>>> struct.pack('=fff', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же.
>>> struct.pack('=3f', 1.0, 2.5, 4.1)
b'\x00\x00\x80?\x00\x00 @33\x83@'
Теперь запакуем разные типы
>>> data = struct.pack('=fiQ', 1.0, 4, 100500)
я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт)
b'\x00\x00\x80?\x04\x00\x00...'
Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа.
>>> struct.unpack('=fiQ', data)
(1.0, 4, 100500)
Как видите, ничего страшного!
#lib#basic
🌎 Some octopus species, like the mimic octopus, can rapidly change their color and skin texture to blend into diverse backgrounds or imitate venomous sea creatures. This camouflage is controlled by specialized skin cells called chromatophores, iridophores, and leucophores, allowing them to avoid predators or catch prey. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Parrotfish dazzle reefs with scales in neon blues, pinks, and greens, while the stonefish hides perfectly among rocks thanks to its bumpy, mottled skin. Stonefish toxins can cause serious injury if stepped on. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 The peacock mantis shrimp stands out for its dazzling rainbow armor and lightning-fast punch. Its eyes detect polarized and multispectral light far beyond human vision. This shrimp's punch can shatter aquarium glass and accelerate as fast as a bullet—up to 23 meters per second. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Few animals rival the peacock mantis shrimp for color and camouflage. Its shell displays vivid blues, reds, and greens, helping it blend with coral while startling predators. The mantis shrimp’s eyes detect polarized light and twelve color channels—far more than humans, who see only three. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Arctic hares survive the icy tundra by changing their fur color—white in winter to blend with snow, brown or gray in summer for camouflage. Adults can leap up to 2 meters in a single bound to escape predators. ✨
#animals⚡#adaptation⚡#camouflage
👉subscribe Interesting Planet
👉more Channels
🌎 Harlequin toads flaunt striking black, yellow, and orange patterns to warn predators of their skin toxins, while the common leaf insect mimics green leaves so closely that even its legs resemble plant veins. Scientists have documented over 3,000 species of leaf-mimicking insects worldwide. ✨
#animals⚡#adaptation⚡#camouflage
👉subscribe Interesting Planet
👉more Channels
🌎 The leafy sea dragon, native to southern Australia, blends perfectly with seaweed thanks to leaf-like extensions on its body. These fins don’t propel it but provide camouflage from predators. Leafy sea dragons reach up to 35 centimeters in length and are closely related to seahorses. ✨
#adaptation⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 The orchid mantis of Southeast Asia blends in with flowers thanks to petal-shaped limbs and white, pink, or yellow coloring that matches local orchids. This insect both camouflages from predators and attracts pollinators, which it ambushes for food. ✨
#animals⚡#camouflage⚡#insects
👉subscribe Interesting Planet
👉more Channels
🌎 The Indian leaf butterfly disguises itself as a dead leaf when at rest, with veins and brown patterns mimicking real foliage. When disturbed, it reveals bright blue and orange wings underneath—stunning colors that help startle predators. This butterfly is native to forests in South and Southeast Asia. ✨
#camouflage⚡#adaptation⚡#insects
👉subscribe Interesting Planet
👉more Channels
🌎 The mimicry leaf insect looks exactly like a real leaf, down to brown spots that resemble decay. This remarkable disguise protects it from hungry predators by blending perfectly into the forest floor. ✨
#insects⚡#camouflage⚡#adaptation
👉subscribe Interesting Planet
🌎 Peacock spiders from Australia show off bold, iridescent colors during their unique courtship dances. Males raise flaps on their abdomen that resemble tiny rainbows to attract females. Over 80 species have been identified, each with distinct colors and patterns. ✨
#animals⚡#camouflage⚡#spiders
👉subscribe Interesting Planet
🌎 In Madagascar, the leaf-tailed gecko uses its flattened body and jagged skin edges to blend perfectly with tree bark, becoming nearly invisible to predators. This camouflage is so advanced that even experienced biologists often miss spotting them during the day. ✨
#reptiles⚡#camouflage⚡#Madagascar
👉subscribe Interesting Planet