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 слични објави

Пребарај: #arnex

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

@aseanrussia · Post #258 · 07.02.2023 г., 06:02

Completing his mission in Jakarta Russian 🇷🇺 Ambassador to #ASEAN H.E. Mr. Alexander Ivanov sums up the work being done during his tenure in the article "ASEAN does matter to Russia. A lot". 💬Indeed, for the last several years Russia became an indispensable actor in the Asia Pacific. Our #ASEAN friends understand and appreciate a constructive stabilizing role of Russia 🇷🇺 with no hidden agenda in the region. Our philosophies of international relations, based on the principle of sovereign equality of nations, are similar. ❗️Our practical cooperation reached a status of strategic partnership in 2018, fixed during the Summit of our leaders in Singapore. During these years in addition to existing areas of cooperation, we have managed to launch and actively promote new ones, including Consultations of the High Representatives for Security Issues, Dialogue on ICT Security-related issues,meetings of Tourism ministers and others. In the end of 2021 we successfully held the first ASEAN-Russia Naval Exercises (#ARNEX) in the Indonesian territorial waters. In 2022 we organized a number of events within the framework of ASEAN-Russia Year of Scientific and Technical Cooperation. Dozens of joint projects were implemented and financed by Russia 🇷🇺 in various spheres ranging from agriculture to training of ASEAN health experts and specialists of law-enforcement agencies. We continued to develop practical cooperation between ASEAN and Eurasian Economic Union as well as with Shanghai Cooperation Organization, thus moving the processes of integration of integrations across the huge Eurasian continent. 🔻We firmly believe that #ASEAN-centered mechanisms of cooperation, created in the last 55 years and based on the principles of equality, mutual respect and constructive engagement, including the #EAS, #ARF and #ADMM-Plus, played the pivotal role in stabilizing the region, balancing the interests of all big players and promoting mutual trust, which are prerequisites of the Asia Pacific phenomenon of becoming the main engine of the global economic growth. For many decades there were no hot military conflicts in the region. Largely it is the merit of #ASEAN wisdom and its leading role in shaping multilateral cooperation here. That is why Russia strongly supports #ASEAN centrality in the region not only in words but in deeds. 🤝 🔻There are many internal and external challenges for #ASEAN in the turbulent situation of strategic ambiguity. I am sure that the current Indonesian 🇮🇩 Chair will be able to navigate the “ASEAN ship” through the troubled waters of the Indian and Pacific oceans. 🔗https://www.thejakartapost.com/opinion/2023/02/06/asean-does-matter-to-russia-a-lot.html