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

Пребарај: #wazema

当前筛选 #wazema清除筛选
Addis Standard

@addisstandardeng · Post #21183 · 24.01.2026 г., 20:40

#Update: ‘We leave these accusations to the judgment of conscience’: #Wazema Media rebuffs Media Authority claims after announcement to return license Addis Abeba – Wazema Media (Wazema Radio) has issued a response to the Ethiopian Media Authority (EMA), clarifying that the return of its operating license was a result of a direct order and rejecting allegations of ethical misconduct. In a statement released late Saturday, the media outlet confirmed it had complied with the regulator’s directive while expressing deep disappointment over the measure. “As per the Authority’s order on Thursday to return our license, we have done so today. The [EMA] statement was released within hours of us doing this,” the management of Wazema stated, adding the compliance to return the license was based on the order from the regulator. “We do not believe the measure is correct by any standard. It has saddened us,” the statement further said. https://www.facebook.com/share/p/1HMEgBLLb4/?mibextid=wwXIfr

Addis Standard

@addisstandardeng · Post #21181 · 24.01.2026 г., 17:31

News: #Ethiopian Media Authority announces return of #Wazema Media operating license on allegations of ‘ethical violations’ Addis Abeba – The Ethiopian Media Authority (#EMA) announced today that Wazema Media, commonly known as Wazema Radio, has returned its operational license in Ethiopia. In a statement released on Saturday, the Authority claimed the media outlet returned its recognition and license because it was "unwilling to work while respecting the Ethiopian Constitution and the Media Proclamation, as well as guidelines and professional ethics." The EMA, which had granted Wazema Media an online media license, stated that its decision followed continuous monitoring and "tips and comments" received from the public. According to the regulator, Wazema’s reporting was found to be "contrary to the country's national interest, lacking balance, [and] failing to include responses from federal and regional governments." The Authority further alleged that... https://www.facebook.com/share/p/1HzHJemEWM/

Addis Standard

@addisstandardeng · Post #21527 · 25.02.2026 г., 17:06

News: “Closing independent media outlets like #Wazema and #Addis_Standard is an attack on freedom of expression and democratic principles” – #EPRP The #Ethiopian People's Revolutionary Party (EPRP) has condemned the closure of independent media institutions, describing actions against outlets including Wazema and Addis Standard as “an attack on freedom of expression and democratic principles,” as the Committee to Protect Journalists (#CPJ) called on authorities to immediately restore Addis Standard’s registration, warning that the move amounts to retaliation rather than regulation. In a statement issued today, 25 February 2026, the party said shutting down independent media, revoking licenses of international outlets, and harassing media professionals undermines the country’s democratic trajectory. “Preaching free and democratic elections while banning media, arresting and chasing away journalists, and locking down the civic space is mocking the public... Read more: https://addisstandard.com/?p=55397