Можно ли в 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
🌎 Far below the surface, the deep ocean is home to rare animals like the gulper eel, which can expand its mouth wide to swallow prey whole. The giant squid, once considered a sea monster, can reach lengths up to 13 meters and uses long tentacles to catch fish and other deep-sea creatures. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
👉more Channels
🌎 Deep below the ocean’s surface, the barreleye fish (Macropinna microstoma) has a transparent, dome-shaped head that lets it look upward through its own skull. Its tubular eyes can pivot inside the head to spot prey above, and the fish lives at depths of 600 to 800 meters off the Pacific coast of North America. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
👉more Channels
🌎 In the deep ocean, the frilled shark is one of the rarest living sharks, with an eel-like body and 300 trident-shaped teeth. It lives at depths of 500 to 1,500 meters and was first described in 1884. ✨
#deepsea⚡#animals⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 The vampire squid lives 2,000 to 3,000 meters deep, where sunlight never reaches. It uses filaments to sense drifting food, not for hunting. Despite the name, it doesn’t suck blood—its dark color and cape-like web inspired the name. This rare cephalopod has the largest eyes relative to body size in the animal kingdom. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
👉more Channels
🌎 Some deep-ocean animals are so rare that they’re known from only a few specimens. The barreleye fish, for example, has a transparent head and tubular eyes that point upward to spot prey above. It’s found at depths of 600 to 800 meters and can rotate its eyes inside the skull to look forward or up. ✨
#deepsea⚡#animals⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Far below the ocean’s surface, the dumbo octopus glides using ear-like fins on its head. This rare deep-sea animal lives at depths of 3,000 to 4,000 meters and grows up to 30 centimeters long. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
🌎 In the midnight zone over 1,000 meters deep, the comb jelly Bathocyroe fosteri drifts through pitch-black water. Its transparent body is nearly invisible, but rows of cilia beat in waves, scattering light like a rainbow. Researchers first collected specimens near the Bahamas in the 1980s. ✨
#deepsea⚡#animals⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 Shrouded in darkness, the “midnight zone” of the ocean lies below 1,000 meters, where sunlight can’t reach and pressure crushes like a dozen elephants. Creatures here glow with bioluminescence and withstand freezing cold, revealing how life adapts to our planet’s most mysterious depths. ✨
#ocean⚡#bioluminescence⚡#deepsea
👉subscribe Interesting Planet
🌎 Vampire squid live more than 2,000 meters below the ocean’s surface, where sunlight never reaches. This deep-sea animal uses long, webbed arms and blue bioluminescent light to confuse predators. Vampire squid can survive with very little oxygen, thriving in one of the planet’s most extreme habitats. ✨
#oceanlife⚡#deepsea⚡#animals
👉subscribe Interesting Planet
👉more Channels
🌎 The barreleye fish, found at depths up to 800 meters, has a transparent head that lets its tubular eyes rotate upward to spot prey. Its eyes can point forward or straight up, helping it see bioluminescent animals in the dark. The barreleye reaches about 15 centimeters in length. ✨
#deepsea⚡#animals⚡#fish
👉subscribe Interesting Planet
👉more Channels
🌎 The fangtooth fish prowls ocean depths over 5,000 meters below the surface. Its oversized teeth are so long they can’t fit in its mouth, forcing the fish’s brain to sit lower in the skull. Despite its fearsome appearance, this deep-sea predator rarely grows longer than 18 centimeters. ✨
#ocean⚡#deepsea⚡#fish
👉subscribe Interesting Planet
🌎 Giant isopods, distant relatives of the common pillbug, inhabit the deep ocean at depths exceeding 500 meters. These armored scavengers can reach up to 50 centimeters in length, surviving on the remains of dead sea animals that sink to the seafloor. ✨
#oceanlife⚡#deepsea⚡#biodiversity
👉subscribe Interesting Planet