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

Пребарај: #toncommunity

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

@tonlines · Post #6856 · 19.04.2025 г., 17:00

STON.fi Celebrates Successful Event in Tbilisi #TON#Tbilisi#TONCommunity At the recent meet-up in Tbilisi, STON.fi brought together the TON community with passionate discussions and showcases of innovative projects. The event, co-hosted by TON Georgia, highlighted the diversity of voices contributing to the growth of the TON ecosystem. Source: link @tonlines

TON Crypto News

@toncoin_rap · Post #195 · 20.10.2024 г., 09:19

🎧⤴ 💎 Telegram’s Crypto Bot Launches Fee-Free Coin Swaps – Best Rates on TON and Beyond! Telegram’s popular Crypto Bot introduced a groundbreaking Swap feature, enabling seamless exchanges of cryptocurrencies, including TON, at optimal market prices with 0% commission. This new feature empowers users to swap tokens effortlessly, catering to the needs of both seasoned traders and beginners. As Telegram strengthens its ties with The Open Network (TON), this development marks a significant step towards making zero-fee crypto trading more accessible and user-friendly. TON, Telegram, and crypto swaps headline this exciting update. Chorus: Swap it, drop it, no fees, we poppin’, Crypto bot’s live, TON fam’s watchin’. Best market rates, yeah, that’s the notion, Zero percent, ridin’ this motion. Verse 1: Telegram’s bot, now it’s all in play, Swappin’ TON coins without delay. Zero fees stack, in a major way, Crypto’s here to stay, what more to say? Swipe right, the trades ignite, Swappin' at the best rates, day or night. TON on deck, the moves in sight, Crypto bot’s game changin’, feelin’ right. Chorus: Swap it, drop it, no fees, we poppin’, Crypto bot’s live, TON fam’s watchin’. Best market rates, yeah, that’s the notion, Zero percent, ridin’ this motion. Verse 2: From TON to ETH or BTC, quick like a flash, One tap on Telegram, and the coins clash. Zero fees givin' more green in the stash, Crypto bot’s hustle, bringin’ in cash. Telegram links up with TON, Best swaps, no cap, just get it done. In the market, bots always on the run, Swappin’ coins, and we're havin' fun. Chorus: Swap it, drop it, no fees, we poppin’, Crypto bot’s live, TON fam’s watchin’. Best market rates, yeah, that’s the notion, Zero percent, ridin’ this motion. Verse 3: Telegram and TON, now we’re connectin’, Coins on the move, the fam’s respectin’. Best rates, zero fees, no second-guessin’, Crypto's risin', it's impressin'. Swap so quick, it’s like a race, Crypto bot's here, savin' time and space. TON's in the mix, the market’s embrace, With zero fees, everyone finds their place. Chorus: Swap it, drop it, no fees, we poppin’, Crypto bot’s live, TON fam’s watchin’. Best market rates, yeah, that’s the notion, Zero percent, ridin’ this motion. Bridge: TON in the mix, we set the tone, Zero fees, we break the stone. Crypto bot's king on this throne, This is the future, watch it be known. #TONCommunity#CryptoSwap#TON #TONCryptoNewsRapStyle 🎧@toncoin_rap

🙏SBT ONTON in real time! 🔍 Our chat has a bot that monitors the emergence of new SBTs in real time — they appear instantly along with passwords! ❤️ No need to search for them in different chats anymore - just join our community and get valuable Soul Bound Tokens to your wallet, so that you can get a drop for them later! 🟣Claim your SBT ONTON now! #TON#ONTON#SBT#Airdrop#Web3#TONCommunity