Можно ли в 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
🪐 Nearly 400 light-years from Earth, the bizarre exoplanet HD 189733b endures violent weather, with winds reaching up to 8,700 kilometers per hour. Its atmosphere contains silicate particles, causing glass rain that whips sideways at supersonic speeds, giving the planet an eerie, cobalt-blue hue. ✨
#exoplanet⚡#weather⚡#glass
👉subscribe Universe Mysteries
🪐 The peculiar exoplanet GJ 1214b, orbiting a red dwarf 48 light-years away in the constellation Ophiuchus, is shrouded in a thick, steamy atmosphere dominated by water vapor. Observations suggest that this "mini-Neptune" may possess a vast, deep ocean beneath its clouds, making it a striking example of a possible water-world beyond our solar system. ✨
#exoplanet⚡#waterworld⚡#atmosphere
👉subscribe Universe Mysteries
🪐 Exoplanet WASP-12b, about 1,400 light-years away in the constellation Auriga, is a giant planet so close to its star that its atmosphere is being stripped away, creating a glowing, comet-like tail. This tidal distortion makes WASP-12b egg-shaped rather than round, showing how extreme gravity can reshape giant planets when they orbit near their stars. ✨
#giantplanets⚡#exoplanet⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The exoplanet KELT-9b, orbiting a star about 670 light-years away in Cygnus, is one of the most extreme worlds ever found—its dayside temperatures soar above 4,000°C, hotter than some stars. Metal atoms like iron and titanium are vaporized in its atmosphere, creating a blistering, glowing layer of gas that defies what we imagine for planets outside our solar system. ✨
#exoplanet⚡#extremes⚡#heat⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Far from Earth, the exoplanet COROT-7b endures some of the most extreme conditions known: it orbits its star so closely that its surface reaches about 2,000°C, hot enough to melt rock. Scientists believe this heat turns the planet’s rocky crust into a vast, bubbling “lava ocean,” creating a world where rock vaporizes into the atmosphere and rains down as pebbles. ✨
#exoplanet⚡#extremes⚡#lava⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Orbiting the red dwarf LHS 3844, the exoplanet LHS 3844b is a rocky world with no detectable atmosphere and a surface thought to resemble volcanic basalt, much like the Moon’s dark maria. The planet's dayside bakes at over 770°C while its nightside plunges into perpetual darkness, creating a world divided between scorching light and endless night. ✨
#exoplanet⚡#extremes⚡#basalt⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Scientists have identified the exoplanet Gliese 581d, orbiting a red dwarf star about 20 light-years away, as one of the earliest potentially habitable worlds outside our solar system. Gliese 581d lies within its star's habitable zone, where temperatures might allow liquid water to exist, making it a key target in the search for life beyond Earth. ✨
#exoplanet⚡#habitability⚡#water⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Deep in the constellation Scorpius, the star KELT-9 stands out as the hottest known main-sequence star with a planet, blazing at over 10,000°C on its surface. Its intense ultraviolet radiation is so strong that it causes the atmosphere of its planet, KELT-9b, to evaporate away, carving one of the most dramatic examples of a planet literally being stripped by its parent star. ✨
#unusualstars⚡#scorpio⚡#exoplanet⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Just 39 light-years away, the exoplanet TRAPPIST-1e circles its cool red dwarf star in the habitable zone, where temperatures might allow liquid water. Scientists have found that TRAPPIST-1e has a rocky surface and, unlike some of its neighbors, could have the right conditions for life as we know it. ✨
#exoplanet⚡#habitability⚡#TRAPPIST1e⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The white dwarf WD 1145+017 in the constellation Virgo is surrounded by a cloud of dust and debris from a disintegrating minor planet. As the remains slowly spiral in, transit observations reveal dips in starlight—evidence of a cosmic demolition that offers a real-time look at how planetary systems can be torn apart at the end of a star's life. ✨
#whiteDwarf⚡#exoplanet⚡#debris⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Gliese 436b, a Neptune-sized exoplanet in the constellation Leo, is wrapped in a scorching atmosphere where temperatures soar above 800°C. Strangely, its elongated, comet-like tail of evaporating hydrogen trails tens of millions of kilometers behind, evidence of atmospheric escape driven by its star’s relentless heat and radiation. ✨
#exoplanet⚡#evaporation⚡#Leo⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The James Webb Space Telescope has detected carbon dioxide on the exoplanet HD 189733b, a giant world 64 light-years away in the constellation Vulpecula. This is the first time carbon dioxide—a common gas on Earth—has been firmly identified in the atmosphere of an exoplanet, using Webb’s powerful infrared instruments to reveal details about the planet’s chemistry and hint at how its formation differs from giant planets in our own solar system. ✨
#webb⚡#exoplanet⚡#atmospheres⚡#discoveries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels