Можно ли в 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
Houthi for Palestine
🔴 Yemeni Leader says their naval operations imposing huge economic cost on Israeli regime
🔴 Al-Houthi says US airstrikes can't weaken Yemen's deep-rooted military infrastructure
🔴 Al-Houthi says their naval operations deserted Eilat port in great victory for Gaza supporters
🔴 "US defense department acknowledges US failure to prevent military ops, secure waters for Israel"
🔴 Al-Houthi says Americans can destroy houses in criminal attacks but can't break morale of Yemenis
#Houthi
#Israel says it detects missile from #Yemen hours after #Houthi threat to enter war
Addis Abeba - The Israeli Defense Forces (IDF) said it detected a missile launched from Yemen toward Israel early this morning and attempted to intercept it.”
It comes hours after the Houthi in Yemen warned they would directly join the Middle East conflict unless attacks against #Iran ceases and other countries refrain from joining the US-Israeli war coalition against Iran.
The IDF stated this morning that its aerial defense systems were engaged in intercepting the missile, while public alerts were issued urging residents to take precautionary measures.
The development follows a strong warning from the Houthis yesterday night who declared they were “ready to pull the trigger” and enter the conflict directly.
https://www.facebook.com/share/p/1J5wsAcm6E/?mibextid=wwXIfr
Approvata la missione Aspides col voto favorevole di quasi tutto il Parlamento: il Campo Giusto di Giuseppe Conte e Schlein appoggia l'iniziativa militare nel Mar Rosso.
Conte, forse inebriato dalla finta vittoria in Sardegna (le liste del centro-destra hanno raccolto più voti), ha deciso di abbracciare il corso bellicista di Elly&co.
La missione è difensiva, dicono: che succede se ci affondano la Duilio? Perché la nostra missione è coordinata con quella anglo-americana, tutt'altro che difensiva?
Tutelare il traffico marittimo è importante perché l'aumento dei costi dei beni trasportati ricade principalmente sulla povera gente, ma perché non si ragiona sul movente che spinge gli Houthi ad attaccare? Dopotutto la loro è una reazione ai crimini israeliani su Gaza.
Dell'azione diplomatica dell'Italia intanto, per ora, nessuna traccia.
La mia al TG Plus di Cusano Italia TV
#aspides#Houthi#Gaza#Palestina#Israele
https://www.youtube.com/watch?v=Y92awZBdmZ8&ab_channel=SavinoBalzano
Il governo dello #Yemen nomina il ministro delle finanze come nuovo premier mentre gli #Houthi, che controllano gran parte del Paese, lanciano missili contro #Israele e colpiscono le navi nelle principali vie d'acqua; "in solidarietà con la #Palestina".
#Op_ed: Policing Water, Neglecting Land: Why naval power alone cannot save #Red_Sea
In this op-ed, Jafar Bedru Geletu argues the Red Sea crisis persists because Western powers misdiagnose a terrestrial threat as a "maritime domain" issue. He contends that non-state actors now "hold the global economy hostage without ever putting a navy to sea."
The current "littoral-only" doctrine is obsolete, failing to address the "terrestrialization" of warfare—specifically the #Houthi-#Al_Shabaab logistical nexus. Attempting to stop this with frigates is "akin to trying to stop a drug cartel solely by arresting street dealers."
Stability requires integrating #Ethiopia, the region's "center of gravity," into the security architecture. Ultimately, the West must “pivot from containment to integration,” recognizing that the Red Sea is no longer a moat but a bridge.
https://addisstandard.com/?p=55212
News: As #Israel expands in the Horn, #Afar leaders look to #Tel_Aviv for protection amid regional threats — Israel media
Leaders of the Afar community in the Horn of Africa are reportedly looking to Israel for support amid growing security concerns and repression in the region, according to Israeli media outlet Ynet News.
The Afar, a Sunni Muslim tribe spread across #Ethiopia, #Eritrea, and #Djibouti, have faced heightened threats from Iranian-linked actors, including #Houthi recruitment networks and regional arms shipments.
According to Ynet News, an Afar conference held in Ethiopia from 28 to 30 December 2025 brought together political figures, youth and women’s representatives, religious leaders, journalists, and human rights advocates from across Ethiopia, Eritrea, & Djibouti.
The Afar source cited by Ynet News framed the crisis not only as a humanitarian issue but also as a strategic concern, noting that Iranian influence and regional instability,,,
Read more: https://addisstandard.com/?p=54534
https://x.com/SavinoBalzano/status/1966067841360126262?t=Z1K0q2xzolrGXxYD8B8KkQ&s=19
Soldati israeliani in vacanza in Italia per smaltire la tensione accumulata: evidentemente le loro attività a #Gaza (e non solo) comportano un certo “stress da lavoro”.
Mi sembra qualcosa di davvero incredibile: chi lo ha reso possibile? Parliamo di decine di soldati scortati e protetti dalle nostre forze dell’ordine. Se ne sono occupati il Governo, Palazzo Chigi, la Farnesina, la Difesa, il Consolato? Chi ci ha lavorato?
Si tratta di militari che – per stessa ammissione delle più alte cariche dello Stato – sono responsabili di atti definiti inaccettabili ai danni di bambini, civili, giornalisti e così via. E adesso li ospitiamo in vacanza? A casa nostra?
È incredibile che l’informazione non se ne occupi (a parte il Fatto Quotidiano): a nessuno interessa quali pubblici poteri abbiano concorso all’iniziativa? Vi sembra normale? Nessuno ci mette la faccia, nessuno fa domande.
Allora io propongo di destinare spiagge anche ai miliziani di #Hamas, a qualche #Ezbolla, agli uomini #Houthi. Perché alcuni sì e altri no?
#BattitoriLiberi: dal lunedì al venerdì, alle 17, su #RadioCusano.