Можно ли в 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
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace
6️⃣5️⃣years since Yuri Gagarin’s historic space feat!
🚀On April 12, 1961, the Vostok launch vehicle lifted off from the Baikonur Cosmodrome. This momentous event marked the culmination of the efforts of millions of Soviet citizens – design engineers, scientists, military pilots, doctors, specialists across a wide range of fields, and entire branches of industry. Inside the cramped cabin of the crewed spacecraft was Senior Lieutenant Yuri Gagarin.
At 9:07 am, the four metal arms holding the 287-tonne rocket retracted, and Vostok began its lift-off. It was at that very moment that Gagarin’s famous “#POYEKHALI!”(*Let’s go!) rang out over the radio.
At 9:12 am, the spacecraft separated from the launch vehicle and entered the Earth's orbit. Its speed reached 28,260 kilometres per hour – nearly 8 kilometres per second. Never before had a human travelled so fast.
🎙Just as the spacecraft reached Earth's orbit, Yuri Levitan – the USSR’s iconic radio announcer – solemnly declared to the world:
This is Moscow speaking! The time in Moscow is 10:02 am. We are broadcasting a TASS report on the first human flight into outer space.
On April 12, 1961, the Soviet Union launched into orbit around the Earth the world’s first spacecraft-satellite, Vostok, with a man on board.
The pilot-cosmonaut is a citizen of the USSR, Air Force Major Yuri Gagarin (the extraordinary rank was conferred by Order No. 77 of the USSR Minister of Defence, dated April 12, 1961).
While in orbit, Gagarin recorded his observations and transmitted them back to Earth. Before him lay the planet as no one had ever seen it before: the curve of the horizon, the luminous blue edge of the atmosphere, coastlines, mountain ranges, vast landmasses – all set against the bottomless black void of space.
Almost 90 minutes into the flight, the spacecraft began its descent. At that moment, a highly dangerous emergency arose: the descent module failed to separate immediately from the equipment module. However, as the spacecraft re-entered the dense layers of the atmosphere, the connecting cables between the two sections burned through due to friction, and the descent continued.
At 10:42 am, at an altitude of 7 km, the cosmonaut ejected.
At 10:53 am, Yuri Gagarin landed safely in a field near the city of Engels, around 4 km from the present-day bank of the Volga.
On April 14, 1961, by Decree No. 251/22 of the Presidium of the Supreme Soviet of the USSR, Yuri Gagarin was awarded the title Hero of the Soviet Union, together with the Order of Lenin and the Gold Star medal.
Two days later, the people of Moscow welcomed the space traveller to the Soviet capital with flowers and celebratory banners. By the end of April, Earth’s first cosmonaut embarked on an international tour to share what he had witnessed with people around the world. In the two years following this historic event, Yuri Gagarin visited more than 30 countries, where he was honoured as a true hero. The tour became unofficially known as the “Mission of Peace”.
***
1️⃣0️⃣6️⃣minutes of Yuri Gagarin's flight changed the course of world history.
Just 16 years after the most devastating and bloodiest war in human history, the Soviet people achieved what had only recently seemed impossible – opening the way to space for all humankind.
***
💬 As President Vladimir Putin noted in his message to the participants in the first Russian Space Forum on April 9, 2026:
Yuri Gagarin's spaceflight became one of the great events of the 20th century and opened a new era in the history of human civilisation.
We are sincerely proud of several generations of talented scientists, designers, cosmonauts, military personnel and civilian specialists who stood at the origins of the national space programme and wrote bright, heroic pages in the chronicle of its victories and achievements.
🇺🇳 Since 2011, April 12 has been observed as the International Day of Human Space Flight, proclaimed by the UN General Assembly under resolution A/RES/65/271 in honour of Yuri Gagarin’s legendary mission.
#Gagarin65#FirstInSpace