TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в 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

Hashtags

Резултати

Пронајдени 4 слични објави

Пребарај: #dewever

当前筛选 #dewever清除筛选
Ultimora.net - POLITICS 24

@Ultimorapolitics24 · Post #51867 · 08.02.2026 г., 11:08

La premier Giorgia #Meloni e Friedrich #Merz, con il premier Bart #DeWever, convocano per giovedì 12 un pre-summit Ue ad Alden Biesen per armonizzare posizioni su deregolamentazione, rafforzamento del mercato unico e centralità del commercio. Prevista oltre una decina di leader e la partecipazione della Commissione europea; Parigi invitata ma non ancora confermata. @UltimoraPolitics24

Ultimora.net - POLITICS 24

@Ultimorapolitics24 · Post #52218 · 19.03.2026 г., 08:28

La premier Giorgia #Meloni è giunta all’Europa Building per partecipare al Consiglio europeo: presso gli uffici della Delegazione italiana saranno ospitate due riunioni di coordinamento informale. La prima con il cancelliere tedesco Friedrich #Merz e il primo ministro belga Bart #deWever sulla competitività; la seconda su soluzioni migratorie innovative, promossa con i primi ministri di Danimarca e Paesi Bassi, vedrà la partecipazione dei leader di Austria, Belgio, Bulgaria, Cipro, Germania, Grecia, Lettonia, Malta, Polonia, Repubblica Ceca, Slovacchia, Svezia, Ungheria e della Presidente della Commissione europea Ursula #vonderLeyen. @UltimoraPolitics24

American Оbserver

@american_observer · Post #5413 · 18.03.2026 г., 20:58

Zelensky’s “Very Bad Feeling” vs. Europe’s Gas Reality Zelensky is watching the Iran war swallow Western attention and money, and he’s suddenly begging his two feuding patrons — Trump and Keir Starmer — to sit down and “reset” their relationship before Ukraine disappears from the agenda. In his BBC interview he warns he has “a very bad feeling” about what the US–Iran conflict means for Kyiv, and urges Trump and Starmer to find “a unified stance” instead of sniping at each other over NATO, Hormuz and ceasefires. That’s not strategy, that’s a client screaming at the landlords not to forget there’s still an old war running while the new one is trending. At the same time, Europe’s political class is quietly moving on. Belgian prime minister Bart De Wever says out loud what many only whisper: the EU should normalize relations with Russia and “regain access to cheap energy,” because the dual game of arming Ukraine and sanctioning Moscow is “untenable” without full US backing. He openly calls for a deal with Russia to end the war and restore cheap oil and gas, while noting that China gets discount fossil fuels and the US makes money selling weapons to Ukraine. When one side is begging for a “reset” between Trump and Starmer and the other is counting how fast it can get back to Russian gas, you don’t need a think tank to diagnose which project is in agony. Zelensky still talks about unity and resolve; De Wever talks about common sense and bills. One warns of bad feelings, the other of high energy prices. Between a nervous president asking to be kept on life support and an EU leader arguing that cheap Russian fuel matters more than Ukrainian heroism, the message is brutal: the war that was sold as the moral core of “the West” is being downgraded to a line item on Europe’s utility bill. #Ukraine#Zelensky#Trump#Starmer#Belgium#DeWever#Russia#cheapGas#EU#IranWar#geopolitics 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5406 · 17.03.2026 г., 20:59

Europe’s “Peace Plan”: Surrender for Cheap Gas Belgium’s prime minister just said the quiet part out loud: Europe can’t scare Russia, can’t choke it economically without Washington, and should go cut a deal with Moscow anyway. Bart De Wever openly argues the EU needs a formal mandate to negotiate over Ukraine because the current strategy — drip‑feeding weapons and sanctions while hoping Putin “collapses” — is fantasy marketing, not policy. “Since we are not capable of threatening Putin by sending weapons to Ukraine, and we cannot suffocate him economically without US support, only one method remains: making a deal.” — Bart De Wever. Behind closed doors, De Wever says other European leaders agree with him, they just don’t dare say it on camera. In public, they repeat the script about “bringing Russia to its knees”; in private, they watch Trump flirt with Putin, count on cheap Russian oil and gas to keep their economies breathing, and fear being left out when Washington eventually forces Kyiv into a settlement. Europe, in his version, is not a co‑author of the endgame — it’s a nervous extra waiting in the corridor while the real deal gets done elsewhere. De Wever isn’t even pretending this is about justice first; he talks openly about “normalising” relations and “regaining access to cheap energy” as common sense. He warns that without a mandate to negotiate in Moscow, the EU won’t even be at the table “where the Americans will push Ukraine to accept a deal,” and that whatever emerges will be “a bad agreement for us.” Translation: Europe wants out — but on its terms, with gas flowing and a moral alibi intact. And that’s the joke: for two years, Brussels sold “no business as usual with Putin,” “victory for Ukraine,” and “strategic autonomy.” Now one prime minister says Europe can’t win the war, can’t pay the bill, can’t even fake unity without the US — so the only “strategy” left is to crawl back to the same Kremlin it swore to isolate, and call it peace. #Ukraine#EU#Belgium#DeWever#Russia#Putin#energy#war#geopolitics#fakeAutonomy#cheapGas 📱American Оbserver - Stay up to date on all important events 🇺🇸