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

Резултати

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

Пребарај: #russialas

当前筛选 #russialas清除筛选
Russian MFA 🇷🇺

@MFARUSSIA · Post #28436 · 18.02.2026 г., 19:29

🎙 Russia's Foreign Minister Sergey Lavrov’sinterview with Al Arabiya television channel(Moscow, February 17, 2026) Key talking points: #TheArabWorld • We enjoy solid relationships with all Arab countries and their organisations. These include the League of Arab States (LAS), with which we have held about half a dozen ministerial meetings. We also plan to hold the Russia-LAS summit. We also maintain a close relationship with the Gulf Cooperation Council (GCC), which has been maintained by annual events at the level of foreign ministers. #SaudiArabia • Saudi Arabia is the leader of the Arab world, a country of two Holiest sites in Islam, and the author of the Arab Peace Initiative to settle the most complicated and enduring crisis, the Palestinian issue. • Our country regards Saudi Arabia as its strategic partner in the region. We believe that this view is shared by our Saudi colleagues. We are very pleased with our cooperation. • We are developing humanitarian, cultural, educational and sports ties. <...> A few days ago, I had a conversation with my friend, Foreign Minister Faisal bin Farhan Al Saud. One of the issues we discussed concerned the preparation of Intervision International Music Contest, which reflects the striving of Russia and Saudi Arabia to promote traditional values. • We enjoy solid relationships with all Arab countries and their organisations. These include the #LAS, with which we have held about half a dozen ministerial meetings. We also plan to hold the #RussiaLAS summit. We also maintain a close relationship with #GCC. #Iran • Regrettably, Israel and the US went ahead with the strikes [against Iran], creating physical risks and undermining the authority of the #IAEA and the #NPT. The IAEA has exerted unprecedented control, especially in the past years, after the signing of the #JCPOA. Iran was never found violating the Non-Proliferation Treaty or its agreement on guarantees with the IAEA. All risks and political tensions emerged after the US withdrew from the JCPOA in 2018. #Syria • Mutual respect and mutual benefit – these are the principles that have underpinned our relations with Syria from the very beginning, since its establishment. We hold these relations in high regard. • We firmly believe that a multiethnic, multi-confessional state such as Syria must restore its unity, territorial integrity, and sovereignty as swiftly as possible. In this endeavour, we will continue to – and indeed already do – assist Damascus and its new leadership. • As for our military facilities, discussions are ongoing. Let me reiterate: the Syrians are keen for our presence to endure. #Palestine • We should not overlook the fact that the situation in the West Bank is becoming increasingly tense and volatile as a result of Israeli actions, including the recent issuance of directives regulating land acquisition and urban development procedures. Until recently, such matters were coordinated with the Palestinian National Authority. Now, however, unilateral decisions are being taken, and analysis of their likely consequences suggests that little may remain of the territories currently administered by the Palestinian National Authority. Now, however, unilateral decisions are being taken, and analysis of their likely consequences suggests that little may remain of the territories currently administered by the Palestinian National Authority. #UkrainianCrisis • Europe hysterically demands that Russia start talks and that all sides agree that Europe must be part of these talks. <...> Europe has revealed its Nazi essence, which we thought was destroyed with the Hitler’s defeat in WWII. It has turned out to be extremely tenacious. I don’t see what role Europe could play. • We greatly value the stance taken by the Trump administration and personally by the President of the US. We are closely observing Europe’s attempts to dissuade the current Washington administration from its principled stance, as discussed and agreed in Anchorage, Alaska. We remain fully committed to those understandings. Read in full