Можно ли в 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
⭐️ The AMA session will take place today at 14:00 UTC. Max, the founder of TON Map, will answer your questions and discuss current topics (for ru-speaking) on @ton2k.
There will also be a giveaway of SBTs and other prizes. Don’t miss it!
App | X | Fam chat | Map | FAQ#TONMap
❤️A new giant on the map.
One of the main projects ✅️ of the TON blockchain, one of the largest and most significant initiatives, and one of the top 3 wallets in the blockchain ecosystem, has appeared on the TON and Telegram map!
Secure your spot nearby—this is no coincidence!
App | X | Fam chat | Map | FAQ#TONMap
🖼Sticker Store in Telegram
Introducing Sticker Store – the first Telegram-native platform for tokenized stickers.
Explore Bored Apes, Dogs, Flappy Bird and Blummy stars. And yeah, new characters and collections are coming.
➖Explore Stickers
Soon on TON Map⭐️
App | X | Fam chat | Map | FAQ#TONMap
😎Welcome to TON Map — your land on Telegram
TON Map is the flagship map of TON and Telegram—an advertising-and-gaming ecosystem and a metaverse in the spirit of Sandbox, with its own mechanics and innovations. We bring people and projects together on a living map where you can advertise, express yourself, build neighborhoods with friends, and leave your mark.
You buy a pixel—your place, your revenue-generating land. Brand it, place ads, merge plots into districts, join activities—and, among other things, earn in $TON through a built-in rewards mechanism with on-chain transparency. No clutter: simple, intuitive, and scalable.
⭐️Why people buy pixels
➖Visibility: image + link + description (project / profile / donation / shop)
➖Status: your place is on-chain and publicly visible
➖ Growth: merge pixels into districts + build neighborhoods
➖ Utility: TON Map Pages (free link-in-bio) + landowner perks
➖ Game layer: events, airdrops
➖Rewards: Phase 3 (TON earning from lands) is coming soon — rules are transparent and capped per land to stay sustainable
⭐️Quick start
1) Open mini-app
2) Connect a non-custodial wallet (Tonkeeper / MyTonWallet / TON Space)
3) Choose coordinates → Buy → customize your pixel
⭐️#TONMap Beta FAQ:
• What is TON Map? (EN) / (RU)
• How to buy land (EN) / (RU)
• How to play & earn (EN) / (RU)
• Roadmap
• Ambassador program
• Content program
• Land Sale / Partnerships
• Security & Scam Alert
⭐️ Official Community Chats:
- English
- Russian
- Persian
⭐️ Official Social Media Profiles:
- Telegram
- X (Twitter)
- YouTube
X • Fam • Map • Pages
😎 TON Map Article Contest
While we’re preparing a new update for the map, here’s a contest where you can win amazing prizes!
📝Write a review article about #Tonmap on Medium, Binance Square, Reddit, Dzen, VC, Facebook, or any other popular publishing platform.
Share the link to your article in our contest thread: Contest Topic.
⭐️Prizes:
➖Top 5 articles: #TON + 100,000 Coins + in-game items
➖Next 10 articles: 100,000 Coins + in-game items
Deadline: April 15, 2025
App | X | Fam chat | Map | FAQ
🤩 TON Map #Partnership with TON Walk!
We are glad to announce this new collaboration with TON Walk - a Telegram-based mini-app that offers a unique twist on movement-based reward systems with the TON blockchain ecosystem at its heart.
Go out to explore the world and check in with the TON Walk mini-app as you go!
🌐 Join @tonwalk_bot and find #TONMap tasks:)
Let’s grow together 🚀
TON Map App | X |Fam chat | Map
😎 Follow the link: TON Map on TON App and click Upvote!
Why is this important?
➖Help TON Map stand out among projects.
➖Accelerate the development of new features for the community.
➖ Every vote counts! Thank you for your support!
🤑5 random accounts will receive bonus coins.
#TONMap#Web3#UpvoteTONMap
App | X | Fam chat | Map | FAQ
💎 England FanToken X TON Map PARTNERSHIP 🎊
Excited to announce England FanToken new #Partnership with TON Map!
❤️ TON Map - a prestigious project, uniting the TON ecosystem on Telegram map, it’s a TMA, memecoin farming, and a large-scale advertising and gaming platform
Big things ahead!
#EnglandFanToken#TONMap#partnerships
😎 TON Map punks #Partnership with NOT Punks!
We are happy to welcome one more partner on our Map (position)!
❤️NOT Punks and TON Map have teamed up to blend digital assets, advertising, and gameplay! Your NOT Punks NFTs aren’t just avatars, they’re elite characters on the TON Map, helping you earn and win!
➖Advertise with NFTs: Promote your NOT Punks on the map!
➖Punk Rush Game: Collect coins, complete quests, and earn rewards in the game and real life!
➖Join the revolution now!
- TNO Coin RU
- TNO Coin Global
- NOT Punks Official
#NOTPunks#TONMap#NFT#GameFi#Web3#JoinTheRevolution
TON Map App | X | Fam chat | Map