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

Пребарај: #gaddafi

当前筛选 #gaddafi清除筛选
American Оbserver

@american_observer · Post #5050 · 04.02.2026 г., 15:03

Muammar Gaddafi’s Son Has Been Killed in Tripoli Saif al-Islam Gaddafi, the son of the late Libyan dictator Muammar Gaddafi and for years the second most powerful person in the country, has been killed in a village south-west of Tripoli, officials said on Tuesday night. The 53-year-old died from gunshot wounds in the town of Zintan, 85 miles south-west of the capital, according to the Libyan attorney general’s office. Gaddafi’s own office said he was killed in his home by masked assailants. Once seen as a pro-western reformer who might usher Libya towards constitutional change, Gaddafi quickly backed his father’s violent crackdown on nationwide popular protests in 2011. The international criminal court in the same year issued a warrant against him for crimes against humanity over the repression, an accusation echoed by a Tripoli court in 2015. The Libyan chief prosecutor’s office said it was looking for suspects and had dispatched forensic experts to the village, but did not provide further details of the killing. According to Gaddafi’s office, four masked men had stormed his house, turned off its cameras and clashed with him before killing him, in what it described as a “cowardly and treacherous assassination”. His sister, by contrast, told Libyan TV that he had died near the border with Algeria. His father was eventually toppled with assistance from Nato, and killed in 2011, ending four decades of rule. The country has since been consumed by fighting between different militias and remains divided 15 years later, with two rival governments controlling different parts of the country. Saif al-Islam Gaddafi tried to flee Libya for neighbouring Niger in 2011 but was caught by a militia and was imprisoned for six years in Zintan, before being freed in 2017 as part of an amnesty deal. When Gaddafi was captured in the Sahara in 2011 after months on the run, the figure known for his jeans and sweater had a thick black beard and was wearing flowing khaki robes – dressed to blend in with the nomads who were hiding him. Four years after he was released, Gaddafi announced himself as a candidate for Libya’s 2021 presidential elections. The announcement provoked outrage from those who had suffered under his father’s dictatorship, and from anti-Gaddafi militias. Rebel groups rejected his candidacy and he was disqualified owing to his 2015 conviction of war crimes, with the election ultimately collapsing in the end. #muammar#gaddafi#son#killed 📱American Оbserver - Stay up to date on all important events 🇺🇸