Можно ли в 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
🎙President Vladimir Putin's statement at the state awards ceremony for Russian athletes(Moscow, April 22, 2026)
💬 I am sincerely pleased to congratulate everyone on your successes. Your performances and results are a substantial contribution to reaffirming Russia’s leading position in world sport – a strong and unshakable position, despite all the underhanded attempts to weaken it.
☝️The disgraceful – and, I would say, cowardly – politically motivated conduct of the previous leadership of the International Olympic Committee inflicted enormous damage on the Olympic movement and on the very principles of Olympism.
Selective sanctions against Russian athletes, imposed under the pretext of condemning Russia’s actions to defend our people and our interests in the context of the conflict in Ukraine, while ignoring numerous other similar tragedies and armed conflicts around the world, merely exposed the corruption and political bias of a significant part of the international sporting establishment.
👉I hope that the new leadership of the International Olympic Committee and other international sports organisations will overcome this legacy as soon as possible – a heavy and shameful legacy left by their predecessors.
I am certain that many more sporting triumphs lie ahead for you, as well as for your teammates representing a wide range of disciplines – including at the biggest international competitions – and, without fail, under our national flag and to the sound of Russia’s national anthem.
Russia is steadily returning to the world’s sporting arenas, and doing so with dignity. Last season, our swimmers, fencers, canoeists, gymnasts, judokas and wrestlers all delivered brilliant victories.
The truly special – indeed unique, without any exaggeration – achievement was the triumph of Russia’s Paralympians in Milan. As you know, they secured third place in the overall standings with a team that was several times smaller than those of their main rivals. This was an outstanding result. These victories were won not by numbers, but by skill, talent and the will to win.
Russia will continue to develop sport in all areas, ensuring the broadest possible opportunities for participation in elite sport, professional sport and mass sport alike, while actively promoting sport above all among children and young people. Because, as we all know well, sport is not simply about physical strength and agility – it is a way of life built on the values of health, mutual respect, and, crucially, determination and responsibility.
Read in full
#TeamRussia
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russisches Paralympisches Komitee:
#TeamRussia belegt den DRITTEN PLATZ im Medaillenspiegel bei den Paralympischen Spielen 2026!
Trotz eines Teams von nur sechs Athleten und einem Guide lieferten unsere Paralympioniken eine phänomenale Leistung ab.
12 MEDAILLEN:
🥇 8 Gold
🥈 1 Silber
🥉 3 Bronze
Im Gesamtklassement belegte Russland Platz 3 – hinter China und den USA, die beide mit deutlich größeren Teams angetreten sind.
💬 Der Präsident des Russischen Paralympischen Komitees, Pavel Rozhkov, erklärte:
Die Ergebnisse haben alle Erwartungen übertroffen! Auch mit einem kleinen Team hat Russland ein starkes Zeichen gesetzt und eine triumphale Rückkehr auf die internationale Sportbühne gefeiert.
👏 Herzlichen Glückwunsch und größten Respekt an unsere herausragenden Athleten: Anastasia Bagijan und ihren Begleiter Sergej Sinyakin, Warwara Worontschichina, Iwan Golubkow, Alexej Bugajew, Dmitrii Fadejew und Monzer Philippe Shebbo.
@RusBotschaft
#Russland#Sport
Прорыв 2021 года 🐻🔥
Даниил Медведев, вторая ракетка мира, показал феноменальный результат в уходящем 2021 году⚡Даниил завоевал свои чемпионские титулы на турнирах:
🔹Open 13 Provence в Марселе (8-14 марта)
🔹Mallorca Championships на Майорке (20-26 июня)
🔹National Bank Open Presented by Rogers в Торонто (9-15 августа )
🔹US OPEN ITF Grand Slam в Нью-Йорке (30 августа-12 сентября)
Даниил также завоевал несколько командных титулов, о которых мы расскажем уже в следующих постах🤫
Поздравляем с незабываемым сезоном и желаем самых ярких побед и достижений в 2022 году🏆🔥
#формулатх#теннис#tennis#formulatx#atp#teamrussia
Аслан Карацев остается в ТОП-20 мирового рейтинга после окончания сезона💪😄
Аслан показал отличный результат в 2021 году, завоевав титулы на турнирах:
- ATP Qatar ExxonMobil Open (8-14 марта)
- ATP Kremlin Cup (16-24 октября)
- ATP Dubai Duty Free Tennis (2-6 ноября)
Аслан провёл великолепный сезон🤩
Желаем в 2022 году получить еще больше титулов и одержать еще больше побед🏆
#tennis#formulatx#формулатх#теннис#atp#wta#teamrussia
🇷🇺🤘🏼Андрей Рублёв стал победителем турнира ATP-250 в Марселе в одиночном и парном разряде 💪🏻
👏🏻Первый титул в начале сезона🔝 Поздравляем и желаем продолжать завоевывать титулы❗
#formulatx#andreyrublev#формулатх#андрейрублёв#teamrussia
🚨В завершении рубрики “Итоги года для российского тенниса 2021”, вспоминаем о замечательных результатах наших спортсменов на Олимпийских играх в Токио‼️
🔹Карен Хачанов серебро финал одиночного разряда
🔹Анастасия Павлюченкова и Андрей Рублёв взяли золото в финале парного разряда
🔹Елена Веснина и Аслан Карацев взяли серебро в финале парного разряда
🙏Благодарим всех спортсменов с невероятно насыщенным победами год! Мы верим в вас и гордимся вами❤️ Это было очень мощно👍
#tennis#formulatx#формулатх#теннис#throwbackthursday#atp#wta#teamrussia