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

Резултати

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

Пребарај: #russiarwanda

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

@MFARUSSIA · Post #29342 · 18.04.2026 г., 13:33

🇷🇺🇷🇼 On April 18, Foreign Minister Sergey Lavrov had a meeting on the sidelines of the Antalya Diplomacy Forum with Minister of Foreign Affairs and International Cooperation of the Republic of Rwanda Olivier Nduhungirehe. The Ministers reaffirmed their mutual commitment to steadily develop bilateral cooperation and discussed current issues of enhancing traditionally friendly Russia-Rwanda relations with a focus on expanding trade, economic and humanitarian ties including cooperation in peaceful use of nuclear energy, education and personnel training. FMs expressed shared readiness to further interaction in international affairs, including at the UN and in other multilateral venues to resolve global and regional issues. #RussiaRwanda

Russian MFA 🇷🇺

@MFARUSSIA · Post #29339 · 18.04.2026 г., 11:18

🇷🇺🇷🇼 Russian Foreign Minister Sergey Lavrov and Minister of Foreign Affairs and International Cooperation of Rwanda Olivier Nduhungirehe held a meeting 📍 Antalya, April 18 #RussiaRwanda

Russian Embassy in Asmara

@rusembasmara · Post #536 · 11.11.2024 г., 18:24

#Day1 🗓 On November 9, Russia's Foreign Minister Sergey Lavrov held a series of bilateral meetings with his counterparts from the African nations on the sidelines of the First Ministerial Conference of the Russia-Africa Partnership Forum in Sochi, including: #RussiaMali 🇷🇺🇲🇱 Minister of Foreign Affairs and International Cooperation of the Republic of #MaliAbdoulaye Diop. The Parties discussed a range of issues concerning the further strengthening of Russian-Mali relations, which are traditionally friendly in nature. In this context, they examined in detail various aspects of enhancing bilateral trade and economic and investment partnership. Moscow and Bamako also reaffirmed their unwavering commitment to deepening political dialogue and enhancing coordination on key issues within the global and regional agendas at the United Nations and in other multilateral formats. #RussiaUganda 🇷🇺🇺🇬 Minister of Foreign Affairs of the Republic of #Uganda Gen. Jeje Odongo. The Sides discussed in detail the key trends in furthering Russian-Ugandan multifaceted cooperation with a focus on enhancing the mutually beneficial trade, economic and investment partnership, as well as developing joint projects in energy, mining, agriculture, science, education, medicine, and digital technologies. They also reaffirmed the intent of Moscow and Kampala to strengthen constructive interaction and coordination at the UN and other international venues. #RussiaCameroon 🇷🇺🇨🇲 Minister of External Relations of the Republic of #CameroonLejeune Mbella Mbella. The Parties discussed a range of issues concerning the further strengthening of the traditionally friendly Russia-Cameroon relations. This includes enhancing bilateral trade, economic cooperation and investment partnership, as well as improving the legal framework and implementing promising joint projects. Moscow and Yaounde also reaffirmed their commitment to deepening their trust-based political dialogue and closer coordination on topical international and regional issues at the United Nations and in other multilateral formats. #RussiaCAR 🇷🇺🇨🇫 Minister of Foreign Affairs, Francophonie and Central Africans Abroad of the Central African Republic Sylvie Baipo-Temon. The Sides discussed in detail a range of issues related to advancing the traditionally friendly Russian-Central African relations, focusing on promoting promising projects in mineral exploration and production, agriculture, healthcare, and personnel training. They also reaffirmed Moscow and Bangui’s intent to intensify political dialogue and close coordination at the UN and other multilateral formats while addressing global and regional problems based on the fundamental principles of international law and the UN Charter. Sergey Lavrov and Sylvie Baipo-Temon signed an Agreement between the Government of the Russian Federation and the Government of the Central African Republic on the Mutual Cancellation of Visa Requirements for Holders of Diplomatic and Service Passports, as well as a Memorandum on Consultations between the Ministry of Foreign Affairs of the Russian Federation and the Ministry of Foreign Affairs, Francophonie and Central Africans Abroad of the Central African Republic. #RussiaRwanda 🇷🇺🇷🇼 Minister of Foreign Affairs and International Cooperation of the Republic of #Rwanda Olivier Nduhungirehe. The Parties discussed a range of issues pertaining to further strengthening the friendly Russian-Rwandan relations, with a particular focus on expanding cooperation in trade, the economy, investment, humanitarian matters. Moscow and Kigali also reaffirmed their commitment to deepening political dialogue and maintaining close coordination at the UN to address global and regional issues. The Ministers signed a Russian-Rwandan intergovernmental agreement on visa-free travel for holders of diplomatic or service passports. #RussiaAfrica