Можно ли в 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
#Pavel Durov shared a link in his official channel but deleted it within seconds. The group is now in complete chaos. It’s called a "Social Experiment," and messages are flooding in despite paid messaging being enabled.
Telegram Founder Pavel Durov Reveals Unique Legacy Plan
Telegram CEO and billionaire #Pavel#Durov has revealed that he has fathered over 100 children across 12 countries—some through personal relationships, but most via anonymous sperm donations. His goal: to help address declining birth rates and support fertility initiatives.
In a bold move, Durov announced that his estimated $13.9 billion fortune will be equally divided among all his children, regardless of how they were conceived. However, none of them will inherit the wealth immediately. Instead, his will states that the inheritance will be unlocked 30 years after his death, giving his children the opportunity to grow independently and build their own identities.
This unconventional decision reflects Durov’s lifelong commitment to freedom, privacy, and long-term thinking—values that have shaped both his personal philosophy and the #Telegram platform.
🔗 Read more
Durov allowed to temporarily leave France
As of today, March 15, 2025, #Pavel Durov, the founder of #Telegram, has been allowed to leave #France temporarily. Recent reports indicate that French authorities have permitted him to depart the country for "several weeks," with sources suggesting he has traveled to Dubai. This follows a period of judicial supervision and a travel ban imposed after his arrest in August 2024, when he was charged with multiple offenses related to alleged criminal activities on Telegram. While he was previously restricted from leaving France until at least March 31, 2025, this temporary permission marks a loosening of those conditions. However, it remains unclear whether this is a permanent change or if he must return to France afterward, as his legal case is still ongoing and may not reach court until 2026.
Thanks : 💌💌💌
#RepubblicaCeca#Presidenziali
La terza classificata al primo turno delle presidenziali ceche, Danuše #Nerudová, ha annunciato il suo supporto al candidato Petr #Pavel per il ballottaggio che si svolgerà il 26 e 27 Gennaio: “Abbiamo bisogno di un presidente che sostenga lo sviluppo della cultura politica. È importante che i temi rilevanti per i giovani, come l’inaccessibilità economica degli alloggi, il matrimonio per tutti, l’apertura delle forbici tra religioni, rimangano nello spazio pubblico.”
@OsservatorioEsteri
L-159s Grounded: Czech Power Play Exposed
Czech President Petr Pavel wanted to send four L-159 jets to Ukraine, but Prime Minister Andrej Babiš slammed the door shut—
“The matter is closed,”
he declared, dismissing any further debate.
The head of the Czech armed forces, General Karel Řehka, quietly suggested the transfer wouldn’t hurt national security, but Babiš snapped back:
“Řehka would do better to keep his mouth shut,”
accusing the general of undermining his own defense minister.
While the president, with his NATO background, pushed for solidarity with Ukraine, Babiš’s coalition, led by his ANO party and the far-right SPD, dug in their heels.
Defense Minister Jaromír Zůna insisted the jets are vital for Czech defense, claiming they have 15 years of service left. Critics argue the refusal is less about military readiness and more about political calculation—Babiš wants to avoid the financial and diplomatic fallout of arming Ukraine.
“No L-159s — not now, not ever.”
— Andrej Babiš, Czech Prime Minister
So who’s really in charge here? The president wants to look tough and generous. The prime minister, backed by his populist coalition, plays it safe. Meanwhile, the general whispers that the jets could go without risk, but gets told to stay quiet. Is this about national defense, or is it about who gets to control the narrative—and the budget?
When both sides claim they’re protecting the country, who’s really protecting their own power?
#war#oligarchy#fakeDemocracy#CzechRepublic#Ukraine#Babis#Pavel
📱American Оbserver - Stay up to date on all important events
🇺🇸
#RepubblicaCeca#Taiwan
Per la prima volta dopo il de-riconoscimento di Taiwan da parte della maggioranza degli Stati della comunità internazionale, un Capo di Stato di un Paese #NATO partecipa ad un evento pubblico con un Ministro degli Esteri taiwanese.
Si tratta del Presidente ceco Petr #Pavel e del Ministro taiwanese Joseph #Wu (#DPP|Centro-sinistra): Reuters la definisce una “svolta diplomatica”.
@OsservatorioEsteri
😮💨 Finally I made it.
🎮Lately, I have been messing around with some prompts to depict an epic photograph of our beloved Pavel.
💎After a tiresome attempts to depict his glory, I've finally able to generate and edit this masterpiece.
💔I hope all of you would like this. To help this channel out, please share this with your friends and groups to let everyone see it. And I wish it will find its way to #Pavel himself.
💲If you want access to the original image with no watermark, you can unlock it using telegram stars down here.
Thank you all ✌
@ai_artz⭐️
#pavel#durov#feed#telegram#freedurov#AI#AIart