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

Резултати

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

Пребарај: #saarc

当前筛选 #saarc清除筛选
Russian Mission to ASEAN

@aseanrussia · Post #1653 · 30.05.2025 г., 06:47

🎙 Foreign Minister Sergey Lavrov’s remarks at the meeting with delegation of the Permanent Committee of the International Conference of Asian Political Parties (Perm, May 29, 2025) 💬 Sergey Lavrov: Dear colleagues, dear friends, This is the year when the International Conference of Asian Political Parties commemorates its 25th anniversary. And because of their reputation and their authority, they are a platform for exchanging views and experience in the context of party-to-party cooperation. Cooperation at this level is one of our priorities. It's a very useful addition to the so-called classical diplomacy and that contributes a lot to promoting mutual trust, mutual understanding between peoples. The creation of the conference is a signal, a very clear signal to the entire world. And very timely response to reconsider the place of the Asian countries in international and global developments. We assess very positively the increase of the political work of your conference. And we see with pleasure the sustainable process of expanding your influence in the continental architecture, in the architecture of regional organizations, some of which are experiencing erosion of their influence, if not degradation, since they abandoned practically all of the key principles of the UN Charter. I have in mind such organizations on our Eurasian continent as the European Union, which became more Euro-Atlantic than Eurasian following NATO. <...> In the last 10-15 years, all these principles including equal and indivisible security, including the statement that no one, be it the country or organization, should prepare to dominate in Europe, all this was abandoned, violated. 🌐 We need Eurasia of course. And by the way, Eurasia is the biggest, the richest continent. The continent which, unlike Africa and Latin America, is home of several world civilizations with thousands and thousands of years of history. <...> #Eurasia is the only continent which doesn't have any universal continental structure, like African Union in Africa, like CELAC in Latin America. We have quite a lot, many integrational movements, organizations which address security issues, like Shanghai Cooperation Organization, #ASEAN, Collective Security Treaty Organization (#CSTO), Commonwealth of Independent States (#CIS) and the Gulf Cooperation Council (#GCC), the South Asian Association for Regional Cooperation (#SAARC) and there is no umbrella. We are very much in favor of promoting party-to-party dialogue. Our ruling party, United Russia, in cooperation with other parliamentary parties and their fractions is promoting very actively this kind of cooperation. And I will highlight the initiative of United Russia of last year, when they convened a meeting of various parties to consider methods of fighting the new forms of colonialism and neo-colonialism. <...> A movement created on the basis of the conference, which is called "Freedom of Nations". ☝️ The inadmissibility of neo-colonial forms of exploitation is one of the agenda items of the Group of Friends of the UN Charter. Last year, we initiated, through this group, the resolution of the UN Committee on Decolonization. The draft resolution supported by this committee was accepted by the UN General Assembly. <..> A clear majority supported it. The idea is to announce the 14th of December, the day of the adoption of The Declaration on the Granting of Independence to Colonial Countries and Peoples of 1960, as a date of fighting the new forms of neo-colonialism. Сolonial exploitation was very blunt. Slaves, you know, digging the resources and leaving the countries in very poor condition. If you take the economic system in the world, countries, especially in Africa, mostly produce, they provide natural resources to the western countries We would like to promote the movement to resolve this injustice. Without fighting any country, we never want to isolate any country from cooperation, but cooperation must be based on equal footing, just principles. 🤝 We express our readiness to cooperate with your conference.

Embassy of Russia in Singapore

@rusembsg · Post #4100 · 01.06.2025 г., 07:02

🎙 Foreign Minister Sergey Lavrov’s remarks at the meeting with delegation of the Permanent Committee of the International Conference of Asian Political Parties (Perm, May 29, 2025) 💬 Sergey Lavrov: Dear colleagues, dear friends, This is the year when the International Conference of Asian Political Parties commemorates its 25th anniversary. And because of their reputation and their authority, they are a platform for exchanging views and experience in the context of party-to-party cooperation. Cooperation at this level is one of our priorities. It's a very useful addition to the so-called classical diplomacy and that contributes a lot to promoting mutual trust, mutual understanding between peoples. The creation of the conference is a signal, a very clear signal to the entire world. And very timely response to reconsider the place of the Asian countries in international and global developments. We assess very positively the increase of the political work of your conference. And we see with pleasure the sustainable process of expanding your influence in the continental architecture, in the architecture of regional organizations, some of which are experiencing erosion of their influence, if not degradation, since they abandoned practically all of the key principles of the UN Charter. I have in mind such organizations on our Eurasian continent as the European Union, which became more Euro-Atlantic than Eurasian following NATO. <...> In the last 10-15 years, all these principles including equal and indivisible security, including the statement that no one, be it the country or organization, should prepare to dominate in Europe, all this was abandoned, violated. 🌐 We need Eurasia of course. And by the way, Eurasia is the biggest, the richest continent. The continent which, unlike Africa and Latin America, is home of several world civilizations with thousands and thousands of years of history. <...> #Eurasia is the only continent which doesn't have any universal continental structure, like African Union in Africa, like CELAC in Latin America. We have quite a lot, many integrational movements, organizations which address security issues, like Shanghai Cooperation Organization, #ASEAN, Collective Security Treaty Organization (#CSTO), Commonwealth of Independent States (#CIS) and the Gulf Cooperation Council (#GCC), the South Asian Association for Regional Cooperation (#SAARC) and there is no umbrella. We are very much in favor of promoting party-to-party dialogue. Our ruling party, United Russia, in cooperation with other parliamentary parties and their fractions is promoting very actively this kind of cooperation. And I will highlight the initiative of United Russia of last year, when they convened a meeting of various parties to consider methods of fighting the new forms of colonialism and neo-colonialism. <...> A movement created on the basis of the conference, which is called "Freedom of Nations". ☝️ The inadmissibility of neo-colonial forms of exploitation is one of the agenda items of the Group of Friends of the UN Charter. Last year, we initiated, through this group, the resolution of the UN Committee on Decolonization. The draft resolution supported by this committee was accepted by the UN General Assembly. <..> A clear majority supported it. The idea is to announce the 14th of December, the day of the adoption of The Declaration on the Granting of Independence to Colonial Countries and Peoples of 1960, as a date of fighting the new forms of neo-colonialism. Сolonial exploitation was very blunt. Slaves, you know, digging the resources and leaving the countries in very poor condition. If you take the economic system in the world, countries, especially in Africa, mostly produce, they provide natural resources to the western countries We would like to promote the movement to resolve this injustice. Without fighting any country, we never want to isolate any country from cooperation, but cooperation must be based on equal footing, just principles. 🤝 We express our readiness to cooperate with your conference.