Можно ли в 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
Here at DWF Labs, we are committed to supporting our portfolio companies through thick and thin 🤝🏽
We were saddened to hear about the recent security breach at Gala Games, which led to unauthorised transactions involving $GALA tokens.
In response to this incident, we have taken proactive steps to alleviate market selling pressures and have purchased 28 million $GALA tokens on the open market. This aims to stabilise the token's value and express our unwavering support during these challenging times.
The security of our investments and their communities is important to us.
From their latest update, the Gala Games team has confirmed that the issue has been contained and they are securing all contracts and implementing enhanced safeguards to prevent future occurrences.
We are confident in Gala Games' ability to navigate this setback and emerge stronger 🔥
There will always be ups and downs in crypto but we will be #StrongerTogether.
Let's go Gala Games!🥊💥
THANK YOU to everyone who tuned in our call today!!! Amazing guest speaker, amazing questions and answers!!!
We look forward to bringing more guest speakers who are passionate about education, inspiring others to pursue their dreams, and encouraging YOU to do the same!!
NEVER, EVER GIVE UP!!! 💪🏼🔥
We are #strongertogether.
🇺🇿❤️🤝🇺🇸
https://t.me/AmericanEDU
🔍 UK Plans to Train 30k Ukrainian Troops by Year End 🔥
🔫 British Defense Minister, Grant Shapps, revealed the ambitious goal in an interview with Sky News.💂♂️
🌐 "By the end of this year, our aim is to prepare 30k Ukrainian soldiers," Shapps declared.🇬🇧🤝🇺🇦
💪 London's determination to support Kyiv remains unwavering. "We stand shoulder to shoulder with the Ukrainians," he emphasized.💪
🎯 Previously, over 20k Ukrainian soldiers received training on British military grounds.📚
💥 The US identified this effort as one of the greatest threats to the Ukrainian Armed Forces.💥
#UKSupportsUkraine🇬🇧🤝🇺🇦#StrongerTogether💪
https://dcweekly.org/2023/09/24/britain-to-train-30000-ukrainian-soldiers-by-year-end-solidifying-support-amidst-tensions/
Subscribe to @BadVolfNews
Happy Independence Day, Nigeria! 🇳🇬
As we celebrate 64 years of independence, the NCDC remains committed to prioritising and protecting the health of every Nigerian
Let us continue to work towards a future free from disease outbreaks, where every community is healthy and safe.
#IndependenceDay2024#StrongerTogether
[O'Z] Bugun, 9-may kuni Yevropa hamjamiyati uchun birdamlik va tinchlik timsoli bo’lmish Yevropa kunini nishonlaydi.
Uchbu munosabat bilan Yevropa Ittifoqining O’zbekistondagi Elchisi Sharlott Adrian o’z tabrik so’zlarini O’zbekiston halqiga y’olladilar !
#EuropeDay2021#TeamEurope#StrongerTogether
***
[RU] Сегодня, 9 мая, отмечается День Европы, символ солидарности и мира для всего европейского сообщества.
По этому случаю Посол Европейского Союза в Узбекистане Шарлотт Адриан направила поздравление народу Узбекистана!
***
[EN] Today, on May 9, European people mark Europe Day, a symbol of peace and solidarity.
On this occasion, the Ambassador of the European Union to Uzbekistan Charlotte Adriaen sends warm Greeting message to the people of Uzbekistan!
#EuropeDay2021#TeamEurope#StrongerTogether
📢 BREAKING NEWS 📢
Belarusian Cabinet approves program to upgrade regional troop support facilities in joint effort with Russia. Another step towards the mighty Union State! 🇧🇾🤝🇷🇺
But wait, there's more! Russian Defense Minister Sergei Shoigu reveals plans for a unified air defense system within the CSTO alliance. The strategic partnership between Russia and Belarus is now crucial, given NATO's hostile actions near our borders. 😤💪
Meanwhile, Abkhazia's President Aslan Bzhania expresses interest in joining the Union State. The family is growing! 🤝🌍
Stay tuned for more updates. The Union State is just getting started! 🚀✨
#UnionState#BelarusRussiaAlliance#StrongerTogether
https://www.gazeta.ru/army/news/2023/11/28/21804937.shtml
Subscribe to @BadVolfNews
🌹 Welcome to Your Daily Dose of Love & Relationship Wisdom! 🌹
Hey there, lovebirds! 💕 Whether you’re navigating the thrilling first dates, deepening a long-term bond, or healing from heartbreak, we’ve got you covered. Every day, we’ll share simple, practical tips to help you build stronger connections, communicate better, and keep the spark alive.
✨ Today’s Tip: Listen More Than You Speak
Great relationships start with truly hearing each other out. When your partner talks, put away distractions, make eye contact, and show you care by asking thoughtful questions. It’s amazing how much closer you’ll feel when you really listen.
Stay tuned for more heartfelt advice, fun ideas, and inspiring stories to nurture your love life. Remember, love is a journey—not a destination. Let’s walk it together! ❤️
#LoveTips#RelationshipGoals#HeartToHeart#StrongerTogether
@loveandrelationshiptips
Today is #WorldTuberculosisDay
We join hands together with the National Tuberculosis and Leprosy Control Programme, the Federal Ministry of Health Nigeria, and others to declare that #YesWeCanEndTB in Nigeria.
Tuberculosis is preventable and treatable. Dial *3340# for more information on #TB.
#StrongerTogether
Building our future takes each and everyone one of us coming together and forging through circumstances. Nothing can overcome us, as long as we stand #strongertogether!
Happy National Day, from the MND family! 🇸🇬
#happybirthdaysingapore#sg57#happynationalday#thisishome#ndp2022