Можно ли в 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
🎙️Russian Foreign Minister Sergey Lavrov:
❗️We cannot afford to rely on the goodwill of our current adversaries, who have openly declared their goal of inflicting a “strategic defeat” on Russia.
☝️ Our position is based on principle. First, experience has taught us not to trust Western promises but to judge solely by concrete actions. Second, recent years have reinforced a crucial lesson: we must never again allow key sectors of our economy, finance and technology to be dependent on the whims of Western suppliers. In the most critical areas – those ensuring our military, food and economic security – Russia must be self-sufficient.
Naturally, this also involves working closely with our strategic partners and allies.
Read in full
#Lavrov#sovereignty#CollectiveWest
@RusEmbMalta Press release
🎙 Russia's Foreign Minister Sergey Lavrov’s remarks and answers to media questions during a news conference on the outcomes of Russian diplomacy in 2024 (January 14, 2025)
***
💬 FM Sergey #Lavrov: We are living in a historical era of confrontation between those who uphold the fundamental principles of international law <...> which have been formulated, set out and put forth in the most important international document – the UN Charter – and those who are not satisfied with that document, who decided <...> that they could not live in accordance with the wishes of the “political West”, <...> those who oppose multipolarity.
President of Russia Vladimir Putin has repeatedly explained the true root causes of the special military operation in Ukraine. We had to begin to repel an attack, a war waged against us by the collective West with the main goal of suppressing competition when Russia re-emerged as its strong rival on the international arena.
Their main goal was to weaken our country geopolitically, creating direct military threats to us right on our borders, on Russia’s native territories, <...> in an attempt to slash our strategic potential and devalue it as much as possible.
The second reason also has to do with the history of the region, only it was more about the people who have lived on that land for centuries. <...> These people were labelled ‘terrorists’ by the current Ukrainian regime, which came to power through a coup d'etat. And when they refused to accept it, that regime launched an all-out offensive against all things Russian. <...>
There has been a revival in efforts to oppose the Western diktat, with emerging economies and new centres of financial power in China, India, ASEAN, the Arab world, and CELAC. This group also includes a resurgent Russia together with its allies from the EAEU, the CIS, and CSTO. This also includes the SCO and #BRICS.
The United States does not want to have any competitors anywhere, starting with the energy sector. <...> The United States and its allies have placed sanctions policies at the core of what they do on the international stage, including regarding Russia. This demonstrates their refusal to engage in fair economic competition and their commitment to using unfair, aggressive practices for suppressing their opponents.
***
#CollectiveWest
The West is intoxicated by its perceived “greatness,” its impunity, and its self-endowed authority to dictate the destinies of peoples worldwide. This reflects arrogance and a disdainful attitude towards the rest of the world. It is yet another brazen assertion that when we speak of “democracy,” it signifies merely one thing – “we do as we please.” <...> It is sheer hypocrisy, dictatorial behaviour, disrespect for the populace.
#UN
UN Security Council reform is needed. Not all countries that bear special responsibility in the global economy, finance, politics, and military affairs are represented in the UN Security Council. It has been pointed out repeatedly that countries such as India and Brazil have long earned permanent Security Council membership on all counts, as has Africa.
#RussiaChina
Russia-China partnership is among the key factors in stabilising the international arena and the ongoing processes that are used, among other things, to escalate confrontation and hostility in international affairs, which is what our neighbours from NATO engage in under US guidance.
#USA#Ukraine
As soon as Donald Trump assumes the presidency and articulates his final stance on Ukrainian matters, we will examine it. <...> The increasing reference to the realities “on the ground” is a development likely to be welcomed.
#RussiaSerbia
Our relations with Serbia are grounded solely in the interests of the Serbian and Russian peoples, as well as our respective states. Our interests align on the vast majority of issues. These relations are rich with specific agreements and projects, including those in the energy sector, approved by our heads of state, governments, and companies.
Read in full.
#Outcomes2024
#Outcomes2024
🎙 Russia's Foreign Minister Sergey Lavrov’s remarks and answers to media questions during a news conference on the outcomes of Russian diplomacy in 2024 (January 14, 2025)
💬 FM Sergey #Lavrov: We are living in a historical era of confrontation between those who uphold the fundamental principles of international law <...> which have been formulated, set out and put forth in the most important international document – the UN Charter – and those who are not satisfied with that document, who decided <...> that they could not live in accordance with the wishes of the “political West”, <...> those who oppose multipolarity.
President of Russia Vladimir Putin has repeatedly explained the true root causes of the special military operation in Ukraine. We had to begin to repel an attack, a war waged against us by the collective West with the main goal of suppressing competition when Russia re-emerged as its strong rival on the international arena.
Their main goal was to weaken our country geopolitically, creating direct military threats to us right on our borders, on Russia’s native territories, <...> in an attempt to slash our strategic potential and devalue it as much as possible.
The second reason also has to do with the history of the region, only it was more about the people who have lived on that land for centuries. <...> These people were labelled ‘terrorists’ by the current Ukrainian regime, which came to power through a coup d'etat. And when they refused to accept it, that regime launched an all-out offensive against all things Russian. <...>
There has been a revival in efforts to oppose the Western diktat, with emerging economies and new centres of financial power in China, India, ASEAN, the Arab world, and CELAC. This group also includes a resurgent Russia together with its allies from the EAEU, the CIS, and CSTO. This also includes the SCO and #BRICS.
The United States does not want to have any competitors anywhere, starting with the energy sector. <...> The United States and its allies have placed sanctions policies at the core of what they do on the international stage, including regarding Russia. This demonstrates their refusal to engage in fair economic competition and their commitment to using unfair, aggressive practices for suppressing their opponents.
***
#CollectiveWest
The West is intoxicated by its perceived “greatness,” its impunity, and its self-endowed authority to dictate the destinies of peoples worldwide. This reflects arrogance and a disdainful attitude towards the rest of the world. It is yet another brazen assertion that when we speak of “democracy,” it signifies merely one thing – “we do as we please.” <...> It is sheer hypocrisy, dictatorial behaviour, disrespect for the populace.
#UN
UN Security Council reform is needed. Not all countries that bear special responsibility in the global economy, finance, politics, and military affairs are represented in the UN Security Council. It has been pointed out repeatedly that countries such as India and Brazil have long earned permanent Security Council membership on all counts, as has Africa.
#RussiaChina
Russia-China partnership is among the key factors stabilising modern international life and the ongoing processes that are used, among other things, to escalate confrontation and hostility in international affairs, which is what our neighbours from NATO engage in under US guidance.
#USA#Ukraine
As soon as Donald Trump assumes the presidency and articulates his final stance on Ukrainian matters, we will examine it. <...> The increasing reference to the realities “on the ground” is a development likely to be welcomed.
#RussiaSerbia
Our relations with Serbia are grounded solely in the interests of the Serbian and Russian peoples, as well as our respective states. Our interests align on the vast majority of issues. These relations are rich with specific agreements and projects, including those in the energy sector, approved by our heads of state, governments, and companies.
#Outcomes2024
🎙 Russia's Foreign Minister Sergey Lavrov’s remarks and answers to media questions during a news conference on the outcomes of Russian diplomacy in 2024 (January 14, 2025)
Read in full
***
💬 FM Sergey #Lavrov: We are living in a historical era or confrontation between those who uphold the fundamental principles of international law <...> which have been formulated, set out and put forth in the most important international document – the UN Charter – and those who are not satisfied with that document, who decided <...> that they could not live in accordance with the wishes of the “political West”, <...> those who oppose multipolarity.
President of Russia Vladimir Putin has repeatedly explained the true root causes of the special military operation in Ukraine. We had to begin to repel an attack, a war waged against us by the collective West with the main goal of suppressing competition when Russia re-emerged as its strong rival on the international arena.
Their main goal was to weaken our country geopolitically, creating direct military threats to us right on our borders, on Russia’s native territories, <...> in an attempt to slash our strategic potential and devalue it as much as possible.
The second reason also has to do with the history of the region, only it was more about the people who have lived on that land for centuries. <...> These people were labelled ‘terrorists’ by the current Ukrainian regime, which came to power through a coup d'etat. And when they refused to accept it, that regime launched an all-out offensive against all things Russian. <...>
There has been a revival in efforts to oppose the Western diktat, with emerging economies and new centres of financial power in China, India, ASEAN, the Arab world, and CELAC. This group also includes a resurgent Russia together with its allies from the EAEU, the CIS, and CSTO. This also includes the SCO and #BRICS.
The United States does not want to have any competitors anywhere, starting with the energy sector. <...> The United States and its allies have placed sanctions policies at the core of what they do on the international stage, including regarding Russia. This demonstrates their refusal to engage in fair economic competition and their commitment to using unfair, aggressive practices for suppressing their opponents.
***
#CollectiveWest
The West is intoxicated by its perceived “greatness,” its impunity, and its self-endowed authority to dictate the destinies of peoples worldwide. This reflects arrogance and a disdainful attitude towards the rest of the world. It is yet another brazen assertion that when we speak of “democracy,” it signifies merely one thing – “we do as we please.” <...> It is sheer hypocrisy, dictatorial behaviour, disrespect for the populace.
#UN
UN Security Council reform is needed. Not all countries that bear special responsibility in the global economy, finance, politics, and military affairs are represented in the UN Security Council. It has been pointed out repeatedly that countries such as India and Brazil have long earned permanent Security Council membership on all counts, as has Africa.
#RussiaChina
Russia-China partnership is among the key factors stabilising modern international life and the ongoing processes that are used, among other things, to escalate confrontation and hostility in international affairs, which is what our neighbours from NATO engage in under US guidance.
#USA#Ukraine
As soon as Donald Trump assumes the presidency and articulates his final stance on Ukrainian matters, we will examine it. <...> The increasing reference to the realities “on the ground” is a development likely to be welcomed.
#RussiaSerbia
Our relations with Serbia are grounded solely in the interests of the Serbian and Russian peoples, as well as our respective states. Our interests align on the vast majority of issues. These relations are rich with specific agreements and projects, including those in the energy sector, approved by our heads of state, governments, and companies.