Можно ли в 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
"El Comando #África de los #EstadosUnidos (#AFRICOM) confirmó que llevó a cabo un ataque aéreo contra las fuerzas de Al-Shabaab el pasado 15 de febrero cerca de Gelib, en la región de Middle Juba en #Somalia, donde se presumía que estaban secuestrados los médicos cubanos Assel Herrera y Landy Rodríguez."
News: Deputy #US Secretary of State to visit #Ethiopia, meet PM Abiy, #AU chair
US Deputy Secretary of State Christopher Landau is set to visit Ethiopia as part of a regional tour that will take him to #Egypt, #Kenya, and #Djibouti between January 24 and February 1, the US Department of State announced.
According to a statement issued by the Office of the Spokesperson, Landau will travel to Ethiopia alongside the Commander of US Africa Command (#AFRICOM), General Dagvin Anderson. During his visit to Addis Abeba, Landau is expected to promote opportunities for US commercial engagement with the Ethiopian government and the private sector.
The statement said the Deputy Secretary will also hold discussions with Ethiopian officials, including Prime Minister Abiy Ahmed, focusing on regional peace and security issues.
In addition, he will meet with AU Commission Chair Mahmoud Ali...
https://web.facebook.com/AddisstandardEng/posts/pfbid02NWzYTrBPpfi2CeqeE5sHCrXFz3UCj3kbNkHU7DBrk9396y48rFcgPGFrdrK2Yjoil
News: #PM_Abiy receives #US Deputy Secretary Christopher Landau, AFRICOM commander as #Ethiopia, US agree to deepen security cooperation
Prime Minister Abiy Ahmed said he received a courtesy visit from US Deputy Secretary of State Christopher T. Landau and the Commander of the United States Africa Command (#AFRICOM), General Dagvin Anderson, describing the engagement as warm and constructive and underscoring the importance of continued collaboration and mutual respect between the two countries.
The visit comes as part of a regional tour by Deputy Secretary Landau that includes #Egypt, #Ethiopia, #Kenya, and #Djibouti, scheduled to run from 24 January to 1 February.
Earlier, Foreign Minister Gedion Timothewos held talks with Landau in Addis Abeba, with discussions focusing on strengthening bilateral relations and exchanging views on regional issues of mutual interest.
During their stay, Landau and General Anderson also visited the International Aviation ....
Read more: https://addisstandard.com/?p=54807
News: #US Assistant Secretary Christopher Landau, AFRICOM commander arrive in #Ethiopia, visit Air Force aviation expo
U.S. Assistant Secretary of State Christopher Landau arrived in Ethiopia today as part of a regional tour that includes #Egypt, Ethiopia, #Kenya, and #Djibouti, scheduled to run from 24 January to 1 February.
The Commander of the U.S. Africa Command (#AFRICOM), General Dagvin Anderson, is also in Ethiopia as part of the visit.
Today, Landau and General Anderson visited the International Aviation Expo organized by the Ethiopian Air Force, according to the Ethiopian National Defense Force (#ENDF). Field Marshal Birhanu Jula, Chief of General Staff of the Ethiopian National Defense Force, also took part in the visit.
The expo showcased aircraft, defense technologies, and related products from the Ethiopian Air Force, the Defense Engineering Industry Group,..
https://www.facebook.com/AddisstandardEng/posts/pfbid021qedgKswfSFzdABsQXmFSvjuiRtWQedXpLYXJysCdk1MBnWvdx4JZJTmEng9jPGRl
#US Forces conduct strike targeting ISIS-Somalia
In coordination with the Federal Government of Somalia, U.S. Africa Command (#AFRICOM) conducted an airstrike targeting #ISIS-#Somalia on March 16, 2026.
The airstrike occurred in the vicinity of the Golis Mountains, approximately 45 km southeast of #Bossaso.
AFRICOM, alongside the Federal Government of Somalia and Somali Armed Forces, continues to take action to degrade ISIS-Somalia’s ability to threaten the U.S. Homeland, our forces, and our citizens abroad.
Specific details about units and assets will not be released to ensure continued operations security. (Source: AFRICOM)
News: #AFRICOM signals deeper #US security, economic engagement in #East_Africa
The Commander of the United States Africa Command (AFRICOM), General Dagvin R.M. Anderson said Washington is seeking to more closely align security cooperation with economic investment across #Africa, citing recent engagements in #Ethiopia, #Kenya, and #Djibouti as part of a broader strategy to address growing security threats while fostering stability and development.
Speaking during a digital press briefing yesterday, General Anderson said he recently concluded a joint visit to East Africa with US Deputy Secretary of State Christopher Landau, where discussions focused on counterterrorism, regional security, and the link between stability and economic growth.
In Ethiopia, Anderson said he attended the Black Lion Air Show marking the 90th anniversary of the Ethiopian Air Force, underscoring what he described as the long-standing US–Ethiopia security partnership....
Read more: https://addisstandard.com/?p=54989
#US shifts Al-Shabaab combat operations from #Djibouti to #Kenya?
The United States and Kenya have launched a $71 million initiative to upgrade the airfield at #Manda Bay, a facility situated directly adjacent to the #Somali border.
While the project focuses on infrastructure in Kenya, analysts view the move as part of a major strategic realignment by US Africa Command (#AFRICOM) to encircle Al-Shabaab threats originating from Somalia, while simultaneously reducing reliance on Djibouti.
Countering Threats from Somalia
The expansion involves extending the runway to 10,000 feet, allowing the base to support large cargo and military aircraft. This capability is designed to boost refueling options and rapid security responses for operations targeting militants in the Horn of Africa.
General Dagvin R.M. Anderson of AFRICOM noted that the project strengthens the security alliance against regional threats....
https://www.ftlsomalia.com/us-shifts-al-shabaab-combat-operations-from-djibouti-to-kenya-somaliland/