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

Резултати

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

Пребарај: #nidoe

当前筛选 #nidoe清除筛选
NIDO Russia (НИДО)

@nido_russia · Post #1937 · 02.02.2025 г., 10:58

🎊🎉🍾🇳🇬🇷🇺 Our beloved organisation, NIDO Russia has been officially accepted as a full member of NIDO Europe yesterday evening 01.02.2025 by the overwhelming majority of the general house which is the supreme organ. We owe this success to our faithful members, the board of trustees, the chairmen Emeritus and stakeholders. Recall that, a tiny group of people prevented this for many years, saying that we must be part of their cabal for our rights to be respected in Europe. We rejected their ideas and protocols, we refused to be gradually assimilated, we took our destiny in our hands, knowing God was on our side. Their condition for peace was that we stoop low and be under them. We rejected that kind of parasitic peace. This group said it was either their way or the highway. We chose the beautiful highway. You must not be a doctor or lawyer or teacher to be part of NIDO Russia or NIDO Europe. Every Nigerian legally residing in Russia has a right to apply to be part of us. Even those who may not yet be fully legal, it is not our duty to judge or condemn them, but rather to guide them (socioeconomically adapt them) towards legalisation and contributing positively to Russia and their families in Nigeria. It is a huge lesson for us all. "Na who give up, na him lose". Nevertheless, we are open to working together with everyone for our common good including those few people who worked against us. It is a new era. What are the benefits of being part of NIDO Europe? 1. The interests of Nigerians in Russia can be represented on a continental level. 2. The interests of the Russian Federation which are also our interests as residents can be represented on a continental level 3. Better negotiating power with the government on matters important to us as Diasporans. 4. Better synergy of efforts towards national development, bilateral trade, foreign direct investments and human capital development. I, on behalf of the executives congratulate us all for this huge achievement including those members who witnessed it live and direct. Yours in service, Dr. Godwin Ibe https://t.me/nido_russia/1937 #NidoRussia#NidoEurope#NIDO#NidoE#Nigeria#Russia

NIDO Russia (НИДО)

@nido_russia · Post #1847 · 26.10.2024 г., 12:30

NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online. Benefits ✅ Take part in shaping Diaspora affairs on a continental level. ✅ Attendance is free ✅ Network with business partners around the European continent ✅ Make new friends/acquaintances ✅ Pitch your ideas ✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level. Take advantage of this golden opportunity. Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up. Dr. Godwin Ibe, Chairman, NIDO Russia +79262385618 *This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom. #nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm

NIDO Russia (НИДО)

@nido_russia · Post #1843 · 23.10.2024 г., 17:59

NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online. Benefits ✅ Take part in shaping Diaspora affairs on a continental level. ✅ Attendance is free ✅ Network with business partners around the European continent ✅ Make new friends/acquaintances ✅ Pitch your ideas ✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level. Take advantage of this golden opportunity. Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up. Dr. Godwin Ibe, Chairman, NIDO Russia +79262385618 *This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom. #nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm

NIDO Russia (НИДО)

@nido_russia · Post #1832 · 19.10.2024 г., 05:01

NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online. Benefits ✅ Take part in shaping Diaspora affairs on a continental level. ✅ Attendance is free ✅ Network with business partners around the European continent ✅ Make new friends/acquaintances ✅ Pitch your ideas ✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level. Take advantage of this golden opportunity. Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up. Dr. Godwin Ibe, Chairman, NIDO Russia +79262385618 *This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom. #nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm