Можно ли в 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
Kevork Almassian warns of the limits to Israeli expansion and the failure of radical politics to resolve the conflict.
Full episode: https://youtu.be/Im-SrR6ggDk
#Israel#EthnicCleansing#MiddleEast#GazaStrip#Lebanon
In an unprecedented move following his shock proposal for the permanent resettlement of the more than two million Palestinians from Gaza to neighboring countries, President Donald Trump announced a controversial plan for the U.S. to take over the Gaza Strip. This statement, made during a press conference with Israeli PM Benjamin Netanyahu, raised eyebrows worldwide. A journalist cornered Trump so he sought Bibi’s help to complete his answer.
#UnitedStates#Israel#DonaldTrump#BenjaminNetanyahu#GazaStrip
🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025)
💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump.
The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange.
Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world.
Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region.
A special emphasis during the conversation was placed on the #UkraineCrisis.
❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods.
In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly.
***
Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts.
It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation.
Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop.
The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement.
In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance.
On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse.
Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact.
🇷🇺🇺🇸#RussiaUS
🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025)
💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump.
The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange.
Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world.
Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region.
A special emphasis during the conversation was placed on the #UkraineCrisis.
❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods.
In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly.
***
Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts.
It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation.
Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop.
The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement.
In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance.
On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse.
Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact.
🇷🇺🇺🇸#RussiaUS
🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025)
💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump.
The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange.
Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world.
Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region.
A special emphasis during the conversation was placed on the #UkraineCrisis.
❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods.
In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly.
***
Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts.
It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation.
Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop.
The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement.
In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance.
On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse.
Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact.
🇷🇺🇺🇸#RussiaUS
🎙Commentary by Aide to the President of Russia YuryUshakov following a telephone conversation between Vladimir Putin and President of the United States Donald Trump (October 16, 2025)
💬Yury Ushakov: Today in the afternoon, Vladimir Putin had a telephone conversation, the eighth one, with US President Donald Trump.
The conversation lasted almost two and a half hours. Clearly, it was a rather substantive and at the same time very open and frank exchange.
Our President started out by congratulating Donald Trump on his successful efforts to normalise the situation in the #GazaStrip. The US President’s peace work has been duly appreciated in the #MiddleEast, in the United States itself, and in most countries around the world.
Naturally, the Russian Side outlined its principled position in favour of a comprehensive Middle East settlement on a generally recognised international legal basis that would ensure lasting peace for all the peoples in that region.
A special emphasis during the conversation was placed on the #UkraineCrisis.
❗️ Vladimir Putin provided a detailed assessment of the current situation, stressing Russia’s interest in achieving a peaceful resolution through political and diplomatic methods.
In particular, it was noted that during the special military operation, the Russian Armed Forces hold full strategic initiative along the entire line of contact. Under these circumstances, the Kiev regime resorts to terrorist methods, attacking civilian targets and energy infrastructure facilities, to which we are forced to respond accordingly.
***
Donald Trump repeatedly emphasised the imperative of establishing peace in Ukraine at the earliest opportunity. The notion that the Russian-Ukrainian conflict has proven the most intractable issue in all peacekeeping efforts of the US President was palpably evident throughout his remarks during the conversation. In this context, he naturally mentioned his successes in settling eight other regional conflicts.
It is noteworthy that one of the US President’s key arguments centred on the premise that the resolution of the conflict in Ukraine would open up tremendous — and he stressed this — tremendous prospects for the development of US-Russian economic cooperation.
Incidentally, both Sides spoke of the profound mutual affinity between the peoples of the two countries, which was so vividly demonstrated during #WWII. It was underscored that the current state of bilateral relations appears paradoxical against this backdrop.
The issue of potential supplies of long-range Tomahawk cruise missiles to Ukraine was also raised. Vladimir Putin reiterated his position that Tomahawks would not change the situation on the battlefield but would inflict substantial damage to relations between our countries, to say nothing of the prospects for a peaceful settlement.
In this context, it is worthy of note that the Presidents discussed the possibility of holding another personal meeting. This is indeed a very significant development. It was agreed that representatives of both countries would immediately begin preparations for the Summit, which could potentially be organised in Budapest, for instance.
On a separate note, it should be mentioned that our President highly praised personal efforts of the First Lady of the United States Melania Trump in reuniting Russian and Ukrainian children with their families and asked the US President to convey his very best wishes to his spouse.
Overall, I would say that the telephone contact between the Presidents of Russia and the United States was quite useful, and the two Leaders agreed to maintain contact.
🇷🇺🇺🇸#RussiaUS