Можно ли в 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
Nubeo и Atari выпустили часы Automatic Atari Asteroids 45th Limited Edition
Дизайн часов отсылает к классической игре Asteroids: секундная стрелка выполнена в форме треугольного космического корабля, а две летающие тарелки являются соответственно часовой и минутной стрелками.
Часы выпущены в пяти расцветках, по 125 экземпляров каждой, но весь тираж уже, увы, распродан по предзаказам.
#Asteroids#Atari#Nubeo
NASA probe will study Jupiter's Trojan asteroids
NASA launched a first-of-its kind mission to study Jupiter's Trojan asteroids
#News#Reuters#NASA#Jupiter#Asteroids
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
🪐 Asteroid (2015) BN509, a giant space rock measuring about 200 meters wide and 400 meters long, speeds past Earth with a shape resembling a giant peanut. Its close flyby in 2017 brought it within just 14 times the distance to the Moon, and radar imaging revealed its rapid rotation and elongated, tumbling motion—features that could make its path unpredictable if nudged by gravity. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 The asteroid (29075) 1950 DA stands out not only for its size but for its unique structure—it’s held together mostly by the tiny forces between individual grains, known as van der Waals forces, rather than by its own gravity. This means that if 1950 DA ever impacted Earth, its loosely-bound material could break apart differently than a solid rock, making its potential effects more unpredictable compared to typical asteroids. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
🪐 The asteroid 1950 DA, about 1 kilometer wide, is hurtling through space with an orbit that brings it close to Earth every few decades. Scientists monitor it closely because its surface is so loosely held together by gravity that only tiny forces—like sunlight pressure—keep it from flying apart, making it a uniquely fragile but potentially dangerous near-Earth object. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
🪐 The asteroid 99942 Apophis, discovered in 2004, is a near-Earth object about 340 meters wide that will make an extremely close pass by Earth in 2029—closer than some satellites! Though it once raised fears of an impact, precise tracking shows it will safely miss us, offering astronomers a rare chance to study such a large asteroid up close as it sweeps just 31,000 kilometers above our planet. ✨
#asteroids⚡#nearEarth⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The asteroid (136617) 1994 CC is a rare triple system, meaning it consists of one main asteroid about 700 meters wide and two smaller moons orbiting it. This near-Earth object follows a path that occasionally brings it close enough to be watched by planetary defense teams, as its complex system could create unpredictable trajectories in the event of a gravitational nudge. ✨
#asteroids⚡#spacehazards⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the constellation Ophiuchus, the asteroid 101955 Bennu harbors boulders on its surface that are actually fragments from a much larger parent asteroid, dislodged by ancient cosmic impacts. Analysis of samples returned by NASA’s OSIRIS-REx mission revealed minerals that interacted with liquid water billions of years ago, revealing Bennu as a time capsule from the dawn of the solar system. ✨
#Bennu⚡#asteroids⚡#OSIRISRex
👉subscribe Universe Mysteries
🪐 Asteroid (1862) Apollo is one of the first discovered "Apollo-type" near-Earth asteroids, regularly crossing Earth's orbit on its journey around the Sun. Measuring about 1.5 kilometers wide, Apollo's path is closely monitored because its changing orbit brings it close enough to qualify as potentially hazardous—a reminder of why astronomers track even ancient space rocks to protect our planet from unexpected encounters. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2013, the small asteroid 2012 DA14, about 30 meters wide, passed just 27,700 kilometers above Earth—closer than many weather satellites. Unlike much larger objects, even an asteroid this size could cause massive regional destruction if it ever struck, which is why astronomers keep careful watch for these smaller, fast-moving near-Earth objects. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (2015) BP513 is a near-Earth object discovered in 2015, which measures around 440 meters across and has an orbit that occasionally brings it within a few lunar distances of our planet. While it poses no immediate threat, its path is tracked closely by astronomers, since an object of this size could cause severe regional damage if it ever collided with Earth—a reminder of why the study and monitoring of such asteroids are vital for planetary defense. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (86039) 1999 NC43 is a massive near-Earth object more than 2 kilometers wide that follows a path bringing it close to our planet's orbit. Its size means that if it ever collided with Earth, it could cause planet-wide devastation, so astronomers keep a careful watch on its movements using radar to track any changes in its trajectory. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels