Можно ли в 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
🌎 Unexpected time anomalies have been observed near strong gravitational fields, like black holes, due to "gravitational time dilation." This effect was confirmed by astronauts using precise atomic clocks, which run slower closer to massive objects compared to those farther away. In 2010, scientists measured time literally ticking faster by 33 microseconds per kilometer higher in altitude on Earth. ✨
#time⚡#physics⚡#relativity
👉subscribe Interesting Planet
👉more Channels
🌎 Time perception can change when moving at high speeds or near strong gravity, as predicted by Einstein's theory of relativity. Atomic clock experiments prove that time really passes more slowly for fast-moving objects or those closer to massive bodies like Earth—astronauts on the International Space Station age about 0.01 seconds less per six months compared to people on the ground. ✨
#time⚡#relativity⚡#physics
👉subscribe Interesting Planet
👉more Channels
🌎 Einstein's theory of relativity reveals that time can actually move slower or faster depending on gravity and speed. For example, atomic clocks on fast-moving satellites tick slightly slower than those on Earth’s surface—a phenomenon confirmed by GPS systems needing corrections due to these time differences. ✨
#time⚡#relativity⚡#physics
👉subscribe Interesting Planet
🪐 In the center of the galaxy ESO 325-G004, astronomers have observed a dramatic example of space-time distortion called gravitational lensing, where the gravity from this massive galaxy bends and magnifies the light of more distant galaxies behind it. This real effect makes background galaxies appear as stretched arcs or multiple images, showing how the fabric of space can be warped by the presence of enormous masses, just as predicted by Einstein’s theory of general relativity. ✨
#wormholes⚡#relativity⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Just outside the event horizon of the supermassive black hole in galaxy NGC 1365, time slows significantly due to the black hole’s intense gravitational pull—a phenomenon called gravitational time dilation. For an observer far from NGC 1365, minutes near the black hole’s edge could translate into hours or even days in regular space, showing how extreme environments can dramatically stretch the flow of time itself. ✨
#blackholes⚡#spacetime⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy M87, where astronomers captured the first-ever image of a black hole, time dilation is so intense near its event horizon (the boundary around a black hole from which nothing—even light—can escape) that an outside observer would see time appear to nearly stop for anything close to the edge. This real effect, predicted by Einstein’s theory of general relativity, means a clock near the event horizon would tick dramatically slower compared to one far away from the black hole. ✨
#timedilation⚡#blackholes⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Time flows differently near massive cosmic objects like black holes—an effect known as time dilation. For example, close to the supermassive black hole Sagittarius A* at the center of our galaxy, clocks would tick slower than on Earth due to its intense gravity; astronauts orbiting just outside its event horizon would age less quickly than those far away, making time itself stretch in extreme environments. ✨
#timedilation⚡#relativity⚡#blackholes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Deep space travelers will experience time differently than people on Earth—a mysterious effect called time dilation. If astronauts took a fast journey to the star Sirius (8.6 light-years away) on a spaceship moving near the speed of light, their onboard clocks would run much slower than those back home, so they would age less during the trip—even while years passed on Earth. This real phenomenon comes straight from Einstein’s theory of relativity and shows how speed itself can turn space voyages into journeys through time. ✨
#timedilation⚡#relativity⚡#spaceships⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Einstein’s theory of relativity predicts dramatic space-time distortions in the violent heart of the galaxy M87, where its supermassive black hole bends not just light, but alters the very flow of time itself. As matter spirals inward, space-time warps so much that signals escaping from near the event horizon—the point of no return—are stretched and delayed, making M87’s core a real example of nature’s most extreme distortions. ✨
#wormholes⚡#spacetime⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Space-time, the "fabric" that weaves together space and time, is not always smooth—giant objects like the supermassive black hole at the center of our galaxy, Sagittarius A*, warp and stretch it so much that both light and time bend around them. These real cosmic distortions, predicted by Einstein’s theory of general relativity, are seen as stars orbit that black hole on paths twisted by its immense gravity, giving us direct evidence that space itself can be bent and curved by massive objects in the universe. ✨
#wormholes⚡#spacetime⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 1977, the Voyager 1 spacecraft passed near Jupiter, and its onboard clocks experienced a tiny but measurable time dilation due to the planet's gravity. This real effect, predicted by Einstein's theory of general relativity, means time ticked just a little slower for Voyager as it flew close to massive Jupiter than it did for clocks far from the giant planet—showing that even in our own solar system, gravity can subtly warp the flow of time. ✨
#timedilation⚡#Jupiter⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 On Mercury, time passes at a different rate than on Earth because the planet orbits much closer to the Sun and feels stronger gravity—a real effect called time dilation. According to Einstein's theory of relativity, stronger gravity slows down the flow of time, so a clock sitting on Mercury's surface would actually run slightly slower than an identical clock on Earth, making time itself stretch differently across the solar system. ✨
#timedilation⚡#relativity⚡#mercury⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels