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

Резултати

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

Пребарај: #tribute

当前筛选 #tribute清除筛选
TONlines – News

@tonlines · Post #7328 · 22.05.2025 г., 14:44

Tribute: Essential Rules for Content Monetization #Tribute#Telegram Tribute channel emphasizes the importance of rules for creators monetizing their Telegram channels. Key rules are summarized in easy-to-understand cards, and further details can be found on their Wiki. Source: link @tonlines

TONlines – News

@tonlines · Post #6895 · 22.04.2025 г., 12:43

Tribute: Launch Your Online Store on Telegram Effortlessly #Telegram#Tribute Tribute offers tools for quickly setting up an online store on Telegram, including features like collections, preliminary shipping cost calculation, and LinkHub for product aggregation. The channel seeks feedback on additional features to enhance user experience. Source: link @tonlines

TONlines – News

@tonlines · Post #7084 · 07.05.2025 г., 14:44

Tribute Makes Payments Easier for Creators #Tribute#Stars The channel @TributeNewsEN highlights a new feature allowing creators to generate web payment links for digital products. These links enable payments in rubles or euros via bank cards, facilitating transactions on social media and other platforms. Source: link @tonlines

TONlines – News

@tonlines · Post #7294 · 20.05.2025 г., 12:35

Tribute Introduces LinkHub for Content Monetization #Tribute#LinkHub Tribute | Monetize your content introduces LinkHub, a centralized platform where users can display products, manage donation goals, and consolidate all paid channels. This tool allows easy sharing of all offerings in a single link. Source: link @tonlines

TONlines – News

@tonlines · Post #7071 · 06.05.2025 г., 16:49

Tribute Empowers Creators with Public API Access #Tribute#webhooks @TributeNewsEN introduces public API access keys, allowing for seamless data integration with external services. Currently, creators can utilize two webhooks for subscription management. Source: link @tonlines

TONlines – News

@tonlines · Post #6914 · 23.04.2025 г., 13:15

Tribute: Celebrating International Creator Day #Tribute#creators Tribute | Monetize your content celebrates International Creator Day on April 23, recognizing the creativity and hard work of content creators. The channel encourages creators to continue entertaining and inspiring audiences. Source: link @tonlines

TONlines – News

@tonlines · Post #6775 · 15.04.2025 г., 12:26

⚡️Tribute: Updated Affiliate Program Announcement #Tribute#affiliate The Tribute channel has updated its affiliate program to help content creators expand their audience and enable partners to earn money by promoting private channels. Detailed information is available on their wiki. Source: link @tonlines

TONlines – News

@tonlines · Post #6719 · 11.04.2025 г., 14:52

Tribute: Voice Actor Shares Success Story #Tribute#voice Tribute shares insights from a voice actor who has mastered monetizing talent using the platform. Learn how they turn their passion for voice acting into income. Source: link @tonlines

Addis Standard

@addisstandardeng · Post #21347 · 09.02.2026 г., 10:47

#Tribute: Professor Asmarom Legesse: Pioneer Scholar Who Illuminated the #Gadaa System to the World Professor Asmarom Legesse, the Eritrean-born anthropologist who redefined African democratic discourse, passed away on January 31, 2026, aged 94. In this tribute, Teferi Tafa notes the Harvard-trained scholar "spent over half a century documenting the #Oromo Gadaa system, dismantling colonial myths that dismissed indigenous #African governance as primitive." The author explains that Asmarom’s works revealed "a sophisticated constitutional order" featuring rotational leadership and term limits. He proved that Gadaa was "a highly developed system of checks and balances... that had governed Oromo society for centuries." Tafa emphasizes that Asmarom’s legacy of "intellectual decolonization" establishes him as a hero to the Oromo and a titan of global anthropology. https://addisstandard.com/?p=55081