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

Пребарај: #bagram

当前筛选 #bagram清除筛选

✨️Ambassador Albert P. Khorev's Interview with “Mehran TV” Full interview available in Urdu Key points: #BilateralTrade 🔸️Over the past two years, the annual trade turnover between #Russia and #Pakistan has amounted to approximately $1 billion USD. Our governments understand that this figure does not reflect our countries' existing potential, and they are making efforts to deepen bilateral cooperation. One effective mechanism in this regard is the Intergovernmental Commission on Trade, Economic, Scientific, and Technical Cooperation, which will hold its 10th milestone meeting in November 2025 in Islamabad; 🔸️There is potential for increased fuel, petroleum products, and grain supplies from Russia to Pakistan, as well as for increased imports of Pakistani textiles, leather, and agricultural products to Russia; #JointProjects 🔸️We are considering a number of infrastructure projects, including the modernization or construction of a new Karachi Steel Mill and railway tracks, as well as the supply of Russian pharmaceutical products, with the option of joint production; 🔸️We look forward to implementing new projects in the energy and transportation sectors. Given the recent establishment of diplomatic relations between Pakistan and Armenia, we believe that a free trade agreement between Pakistan and the #EAEU is possible in the future; 🔸️The successful modernization of the Karachi Steel Mill will pave the way for more productive cooperation; #TradeInNationalCurrencies 🔸️Most of Russia's export operations with friendly countries, including #SCO member states, are conducted in national currencies. The US dollar is slowly but surely losing ground. The process of diversifying payment instruments is succeeding; #SituationInTheRegion 🔸️Russia respects the right of regional countries, including Pakistan, to choose their own foreign policy partners independently. South Asian countries' engagement with the West is an internal matter. However, we consider it inappropriate if such engagement is directed against any state or group of states; 🔸️We have noted the Americans' and their NATO allies' active efforts to return to #Afghanistan after their infamous retreat in 2021. Donald Trump's statements about the U.S.'s desire to retake control of the #Bagram Air Base and his demands that India stop purchasing Russian oil are unacceptable. They represent yet another manifestation of Western neocolonialism; 🔸️The recent SCO summit in China demonstrated the declining influence of extra-regional forces. There is a growing demand for Russian President Vladimir Putin's initiative to establish a Eurasian security system based on the principle of "regional solutions to regional problems;" #MoscowFormat 🔸️The Moscow Format Consultations bring together all of Afghanistan's neighboring countries, including Russia and Pakistan. This regional mechanism has proven its effectiveness. All its members agree that the return of U.S. and NATO military infrastructure to Afghanistan is unacceptable; #Kashmir 🔸️Pakistan and India inherited the Kashmir issue from their British colonial past. We believe that Islamabad and New Delhi should resolve their differences through political and diplomatic means. At the same time, if it receives appropriate signals from both sides, Russia is ready to contribute to improving relations between the two countries and make the necessary efforts in international forums, including the #UN. #RussiaPakistan