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

Резултати

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

Пребарај: #tsahal

当前筛选 #tsahal清除筛选
RT en français

@RTenfrancais · Post #80051 · 25.04.2026 г., 14:00

❌Les médias israéliens diffusent des images qui montreraient une nouvelle frappe de #Tsahal contre la centrale nucléaire iranienne de Bouchehr. RT en français • Osez questionner !

Hashtags

Kurash & Co 🇷🇺

@kurash_and_Co · Post #959 · 26.03.2026 г., 20:22

🟠Échanges réciproques de frappes : l'escalade se poursuit entre #Tsahal et le Hezbollah Alors qu'Israël et le Hezbollah ne semblent avoir aucune intention ni de faire baisser les tensions ni de mettre fin aux combats, malgré les appels de la communauté internationale, les habitants de la capitale libanaise sont descendus dans la rue. Ils protestent contre l’expulsion de l'ambassadeur d’Iran. Les précisions avec notre envoyé spécial sur place, Igor Kourachenko. RT en français • Osez questionner !

Hashtags

Antoine Cléraux

@corrAntoine · Post #621 · 16.03.2026 г., 07:23

⚡️L’offensive israélienne s’élargit au #Liban Les troupes de #Tsahal multiplient les incursions dans le sud du pays. Face à l'urgence, le gouvernement libanais tente d'amorcer une médiation internationale, mais les obstacles restent nombreux. Notre envoyé spécial Antoine Cléraux nous en dit plus sur la situation sur place. RT en français • Osez questionner !

RT France actualités

@rt_fra · Post #40762 · 07.05.2026 г., 09:20

⚡️Tsahal-Hezbollah : frappes au Liban Selon un communiqué de presse de l’armée israélienne, #Tsahal a frappé 15 sites du #Hezbollah dans plusieurs zones du Sud-Liban. RT en français • Osez questionner !

Antoine Cléraux

@corrAntoine · Post #603 · 10.03.2026 г., 21:28

🔴#Tsahal multiplie les ordres d'évacuation sur fond de guerre avec le #Hezbollah libanais Alors que le Sud du #Liban est la cible de frappes israéliennes, les ordres d'évacuation se multiplient dans la région. Pourtant, de nombreux habitants refusent de partir. RT en français • Osez questionner !

American Оbserver

@american_observer · Post #5260 · 02.03.2026 г., 00:59

The IDF confirmed the murder of several high-ranking Iranian officials as part of the military operation : - Ali Shamhani: adviser to the supreme head of security, secretary of the defense council, former commander of the CSIR, minister of defense and head of the navy. Responsible for the Iranian nuclear project and weapons development. - Mohammad Pakpur: the commander of the CSIR, former commander of the ground forces, led the brutal repression of the protests and commanded strategic firing positions against Israel. - Saleh Asadi: the chief of intelligence of the general staff Khatam Al-Anbiya, senior intelligence officer of the Iranian military high command, participated in the development of the strategy against the United States and Israel and in the planning of recent attacks. - Mohammad Shirazi: head of the supreme leader's military office since 1989, in charge of communication between senior commanders and Khamenei. - Aziz Naserizadeh: the Minister of defense, former commander of the air force, was responsible for the defense industry, including long-range missiles and weapons for the proxy forces. - Hossein Jabel Aamelian: head of the SPND (organization for innovation and research in defense), responsible for nuclear, biological and chemical weapons programs. - Reza Mosaffari: former head of the SPND, promoted Iran's efforts to create nuclear weapons. #tsahal#murder#iranian#officials#operation 📱American Оbserver - Stay up to date on all important events 🇺🇸