Можно ли в 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
🔻 Heidi & I wish everyone a Happy #Thanksgiving. May God bless your families and continue to bless the United States. https://t.co/xRnllLEoMQ
November 25, 2021 at 06:00PM
via Twitter
@SenTedCruz
When Congress asked President Washington to declare America's first NATIONAL DAY OF PRAYER & THANKSGIVING, his proclamation of Nov. 26, 1789, noted "it is the duty of all Nations to acknowledge the providence of Almighty God, to obey his will, to be grateful for his benefits, and humbly to implore his protection and favor."
We do well to remember that today.
Have a happy, blessed #Thanksgiving.
"Give thanks to the Lord, for he is good; his love endures forever." Psalm 118:1
Follow me at @SpeakerJohnson
🎆#Thanksgiving Giveaway!
Which coin pumped your bag the hardest this year? 📈
Vote & win a share of $300💰
✅ Follow @HTXCommunity@HTX_Global
🕹RT+ tag 2
🚀 Join and Invite friends to join HTX Telegram Group 1 & Group 2
⬇️ Vote and share which #crypto made you the most money this year
➡️ Vote now HERE
✉️Telegram |
❌X
✉️Announcements |
📷Instagram
💕💕Happy #Thanksgiving! 🐔
Wishing You a Joyous Thanksgiving!
Thank you for the unwavering support from #TPFam and #TokenPocket Partners!
Keep Building! 🏃🏃♂️🏃♀️
【Details】https://twitter.com/TokenPocket_TP/status/1727620906225373326
【Powered By】Crypto Box
Catizen Announcement: Exciting Year Ahead and Thanksgiving Rewards
#Capybobo#Thanksgiving
Catizen Announcement expresses gratitude to its community and anticipates an exciting upcoming year. Bro projects Capybobo and COC are offering Thanksgiving rewards totaling over 2000 USDT.
Source: link
@tonlines
❤️Happy #Thanksgiving day!
💰$1,000 Giveaway To #TokenPocket Users.
We've partnered with symbiosis_fi and Tronify_io for an exclusive DeFi expedition!
🏆 Prize Pool: $1,000 ( $USDT + $TRX)
🎁 Top 10: $200 ( $USDT + $TRX)
🎁 11th-60th: $500 ( $USDT + $TRX)
🎁 51st-100th: $300 ( $USDT + $TRX)
Complete the simple tasks and get a chance to share the rewards!
Tasks on #Glaxe👇
https://galxe.com/TokenPocket/campaign/GCS8ytUEqJ
👉https://tokenpocket.pro
📌 Eligibility: Participants are #TokenPocket users
and must have received an energy subsidy or
rental energy during the campaign period in
order to be eligible for rewards.
🗓️ Nov. 22-Dec. 6
🔥Snatch your ticket for the #DeFi journey now! The more you trade, the better your chances of claiming your share of the $1,000 giveaway!
【Details】https://twitter.com/TokenPocket_TP/status/1727673296546938943
【Powered By】Crypto Box
🎄#GAG#Christmas Event Part 3 👀#Leaks
🚀🍽️Cooking?!
✨Start Time:✅Dec 21, 2:00 AM
🧉#gag🍕#growagarden#leaks🦌#garden#thanksgiving
👨🍳#Christmas-themed FoodCONFIRMED!!!
🍪GingerbreadCookie
🌟Candycane
❄️Wreath
🍖HolidayRoast
♨️HolidayStuffing
🍰Fruitcake
🍳Eggnog
Get ready~~~🚀🚀🚀
Add @APKFreeDownloader_Bot to get any apk you want.
🦃
Every year, Thanksgiving is celebrated on the fourth Thursday of November.
This year that is 27 November.
The tradition dates back to 1621, when Pilgrims and Wampanoag people shared a harvest feast to give thanks for survival and a successful harvest.
[Read more]
@googlefactss#Thanksgiving#History#Gratitude#November27#HarvestFeast
The Essence of Gratitude
Baga Ayyaana Irreechaa Bara 2025 Nagaan Geessan! 🙏💚
Today, our hearts are full. We gather at the hora (living water), holding the green coomii and the yellow daisy flowers of Birraa, to say one thing:
Galanni Waaqaaf haa ta'u.
Look at the beauty of our people! A sea of white, a vibrant display of our culture, all moving as one. This is Irreechaa. 🤍✨
From the wisdom in the blessings of our elders, the Abbaa Gadaas and Haadha Siinqees, to the joyful songs of our youth, Irreechaa is the ultimate symbol of our tokkummaa (unity).
It's a day we forget our differences and remember our shared heritage, our shared prayers, and our shared hope for a brighter future. We are one people, with one heart. 🙌
May this Irreechaa bring peace, unity, and prosperity to all Oromo people and to our beloved Oromia.
Ayyaana Gaarii! ✨
#Irreechaa#Oromo#Thanksgiving#Galata#Birraa#Peace#Oromia
@etbisahusen
Ирреча — ежегодный праздник в Эфиопии 🇪🇹
Фестиваль Ирреча у народа оромо — это главный праздник благодарения в Эфиопии. Он символизирует переход от тёмного сезона дождей к светлому и плодородному сезону Бирраа (весна). На духовном уровне это выражение благодарности Вааке (Творцу) за дарованные благословения и мир.
Сегодня основные торжества проходят у озера Хора-Финфинне в Аддис-Абебе: многотысячные толпы под руководством традиционных старейшин Аббаа Гадаа выполняют главный ритуал — окунают зелёную траву (ирресса) и цветы в воду. Это подношение благодарности и молитва о будущем.
Ирреча — это грандиозное культурное событие, мощное проявление единства и самоидентификации народа оромо. Праздник ярко отражается в традиционной одежде, песнях и танцах, подтверждая глубокую связь с природой и наследием.
Кульминация праздника ожидается завтра, в воскресенье, на его самом священном месте — у озера Хора-Харсаади в Бишофту. Именно там Ирреча становится настоящим днём воссоединения, примирения и надежды.
Irreecha – Annual Thanksgiving Celebration in Ethiopia 🇪🇹
The Oromo Irreecha festival is Ethiopia’s premier thanksgiving celebration, marking the transition from the dark, rainy season to the bright and fertile season of Birraa (spring). Spiritually, it is an expression of gratitude to Waaqa (the Creator) for blessings and peace.
Today, the main celebrations are taking place at Hora Finfinne in Addis Ababa. Vast crowds, led by traditional Abbaa Gadaas, are performing the central ritual: dipping green grass (Irreessa) and flowers into the water as an offering of thanks and a prayer for the future.
This massive cultural event is a powerful manifestation of Oromo unity and identity. The festivities are vividly reflected in traditional attire, songs, and dances, affirming a deep connection with nature and heritage.
The climax is expected tomorrow, Sunday, at its traditional and most sacred site—Hora Harsadi (Lake Harsadi) in Bishoftu. It is there that Irreecha truly becomes a day of reunion, reconciliation, and hope.
https://t.me/Afro_Russians
#Эфиопия#Ирреча#Оромо#Африка#Культура#Традиции#АддисАбеба#Бишофту
#Ethiopia#Irreecha#Oromo#Africa#Culture#Traditions#Thanksgiving#AddisAbaba#Bishoftu