Можно ли в 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
😎Every Open League participant has received their well-deserved reward!
The 6th season of the Open League has recently concluded, leaving participants with not only unforgettable experiences but also well-earned rewards. If you minted a pixel and took part in the activities, your efforts didn’t go unnoticed.
On average, each participant earned $50—a great result for those actively engaging with the TON ecosystem.
Here’s what you got:
➖Normie badges
➖Rewards in Toncoin
➖A unique Web3 experience
🏆 The 6th season showcased incredible growth: 83 TON apps attracted 3.9 million unique active wallets, while the TVL in TON DeFi soared to $6.9 million. This progress is an inspiration for even greater achievements ahead!
⭐️The future is TON Map! Your pixels on the TON Map are already becoming valuable digital assets. Make sure to claim the best spots on the map—this is your chance to make your mark and join one of the most ambitious Web3 projects.
🥳 Stay tuned, join the community, and make history with us!
App | X | Fam chat | Map | FAQ
#TON#Web3#OpenLeague
🎧⤴
TON's Open League Season 6: Airdrops, DeFi Boosts & NFT Wars - Ready for September 12!
The Open League Season 6 on The Open Network (TON) launches on September 12, shifting focus from competition to collaboration. Users can earn airdrops through Normie and Degen rewards by participating in DeFi, apps, and NFTs. Projects across the ecosystem also benefit from extra incentives, helping TON grow towards 500 million wallets and $1 billion in total value locked (TVL).
Verse 1:
Season 6, we ready, TON’s on the rise,
Normie or Degen, you pick your prize.
Airdrops droppin’, apps gettin’ hot,
Buildin’ the ecosystem, ready or not.
Chorus:
500 mil wallets, TVL through the sky,
Open League’s here, reachin’ so high.
DeFi, NFTs, stackin’ the gains,
We all in this mission, breakin' the chains.
Verse 2:
DeFi pools deep, vaults full of gold,
Projects in the League, their stories unfold.
Top three teams, they get the crown,
While communities rise, never backin' down.
Chorus:
500 mil wallets, TVL through the sky,
Open League’s here, reachin’ so high.
DeFi, NFTs, stackin’ the gains,
We all in this mission, breakin' the chains.
Bridge:
Mint that badge, Normie or Degen flow,
Support the ecosystem, let the numbers grow.
TON's the future, crypto on your phone,
Together we rise, blockchain’s new throne.
Verse 3:
NFTs battle, ads on Telegram hit,
DeFi League strong, vaults never quit.
From apps to protocols, we bring the heat,
Season 6 just started, victory's sweet!
Chorus:
500 mil wallets, TVL through the sky,
Open League’s here, reachin’ so high.
DeFi, NFTs, stackin’ the gains,
We all in this mission, breakin' the chains.
#OpenLeague
#DeFiEcosystem
#TON
🎧@toncoin_rap
SettleTON v2.0 Major Release, WEB3 Collaboration, and instructions how to get SBT
🔄 The "v2.0" trend continues — after the recent Ston.Fi v2.0 update, we have the SettleTON project next in line. Below, we'll look at what's been added and updated in the new version:
➖ Improved MID-Risk index: Critical errors were fixed, increasing protocol stability. New #MetaVault system, which optimizes asset storage and makes the reinvestment process more efficient.
➖ Improved reliability: All asset contracts (vaults) now use their own database and infrastructure😊#SettleTON, therefore the balance and quality of reinvestment increases.
➖ A new section has appeared in the bot, in which you can earn RewardPoints (RP) for completing missions from SettleTON and their partners.
🫡SettleTON x WEB3 partnership and increased farming rewards: Team #WEB3 gave a good boost to their pool, you can see and touch it in the bot , in the "Vaults" tab. Also, soon Ston.fi pools will appear in SettleTON (ST), in their post they described the advantages of ST compared to direct deposits through #DEX.
🙏#SBT Hunting, featuring SettleTON: The popular staking project #JVault has launched a campaign in connection with the resumption of The Open League. For simple actions in Quest Bot and DeFi projects — providing liquidity, staking, swaps, subscribing to a channel, we have the opportunity to get an exclusive SBT. Plus, for all these shenanigans, we get additional points and rise in the #OpenLeague ranking, and then
🍔#TON itself.
SettleTON | GitBook | Chat EN | X