Можно ли в 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
🌎 Hidden in the vast cosmic darkness, rogue planets drift alone through space without orbiting any star. These “orphan worlds” form when gravitational forces eject young planets from their home systems. Some estimates suggest our galaxy may contain more rogue planets than stars. ✨
#universe⚡#astronomy⚡#exoplanets
👉subscribe Interesting Planet
🌎 Some distant planets, called rogue planets, drift through space unattached to any star. Astronomers estimate there could be billions of these planets in our galaxy alone. ✨
#astronomy⚡#exoplanets⚡#cosmos
👉subscribe Interesting Planet
👉more Channels
🌎 In 2016, astronomers discovered TRAPPIST-1, a star system 40 light-years away with seven Earth-sized planets. Three orbit in the "habitable zone," where liquid water could exist—making it one of the most promising sites for searching for alien life beyond our solar system. ✨
#astronomy⚡#exoplanets⚡#habitable
👉subscribe Interesting Planet
🪐 The ultra-dense pulsar PSR B1257+12, located in the constellation Virgo about 2,300 light-years from Earth, hosts the first confirmed exoplanets ever discovered. These three worlds—each orbiting this spinning neutron star—endure intense radiation, making them some of the most hostile planets in the known galaxy. ✨
#pulsars⚡#exoplanets⚡#neutronstars
👉subscribe Universe Mysteries
🪐 In 2016, astronomers using the Hubble Space Telescope observed the exoplanet WASP-121b, where temperatures in its stratosphere soar above 2,500°C and molecules such as water vapor exist as glowing, superheated gas. The planet’s intense gravity causes it to stretch into a teardrop shape, while metals like iron and magnesium escape its atmosphere, streaming into space in a shimmering trail. ✨
#exoplanets⚡#atmosphere⚡#extremes
👉subscribe Universe Mysteries
🪐 Exoplanet 2MASS J2126–8140 holds the record for the widest known orbit around its star—about 1 trillion kilometers away, or nearly 7,000 times the distance from Earth to the Sun. This gas giant drifts so far from its host that a single "year" there lasts nearly 900,000 Earth years, exposing it to the coldest, loneliest planetary conditions ever measured. ✨
#exoplanets⚡#extremes⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2023, scientists used the James Webb Space Telescope to study the atmosphere of the exoplanet K2-18b, located about 120 light-years away in the constellation Leo, and detected molecules like methane and carbon dioxide in its thick atmosphere. While this doesn't prove the existence of aliens, these chemicals are considered potential signs that could support life as we know it, making K2-18b one of the most intriguing worlds in the ongoing search for extraterrestrial life. ✨
#aliens⚡#exoplanets⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Some of the loneliest travelers in the galaxy are rogue planets, which drift through space without orbiting any star. Astronomers have detected dozens of these starless worlds, like the giant PSO J318.5-22, floating about 80 light-years from Earth and glowing faintly in infrared as they slowly cool in the darkness. Rogue planets can form the same way as regular planets or be kicked out of their solar systems by gravitational encounters, making them true cosmic wanderers. ✨
#rogueplanets⚡#exoplanets⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have identified the super-Earth exoplanet HD 40307g, located about 42 light-years away in the constellation Pictor, as a promising candidate for life because it may orbit within its star’s habitable zone—the region where temperatures could allow liquid water on the surface. With a mass at least seven times that of Earth and the right distance from its parent star, HD 40307g offers a real-world example of a potentially life-friendly world beyond our solar system. ✨
#exoplanets⚡#habitable⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The star WD 1856+534, located about 80 light-years away in the constellation Draco, is an unusually cool and faint white dwarf orbited by a giant planet-sized object at incredibly close range. This is remarkable because white dwarfs are dense, burned-out remnants of stars like our Sun, and scientists believe any planet this close should have been destroyed during the star’s previous red giant phase—making this system an exceptional survivor among stars. ✨
#stars⚡#white_dwarfs⚡#exoplanets⚡#nasa⚡#galaxy⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2020, researchers using the LOFAR radio telescope detected strange bursts of low-frequency radio waves coming from the red dwarf star GJ 1151, about 26 light-years from Earth. These signals are thought to be created by interactions between the star and an orbiting planet, and while not proof of aliens, such emissions spark excitement because similar interactions could reveal planets that might host life. ✨
#aliens⚡#exoplanets⚡#radio⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The exoplanet LTT 9779b, discovered about 260 light-years away in the constellation Sculptor, is known as an "ultra-hot Neptune" because it orbits its star so closely that its dayside temperature climbs above 1,700°C—hot enough to vaporize metals. Despite these extreme conditions, observations with the Hubble and Spitzer telescopes have revealed a reflective, metallic atmosphere loaded with silicate (rock-forming mineral) clouds, making this planet a shimmering furnace world unlike any found in our solar system. ✨
#exoplanets⚡#extremes⚡#neptune⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries