Можно ли в 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
😄Feature
➖➖➖➖➖➖
🔘A feature is an element of something interesting or important.
🔜The number of parks is an important feature of the city.
It it also used as a general label for the parts of our faces.
🔘My big nose is my least favourite feature.
🔜When we want to say what is included in something, we use feature. Often it's important that they're there.
🔘This phone features an amazing camera.
🔜Just remember, we use the word feature to talk about interesting or important things.
#feature👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
😄Feature
➖➖➖➖➖➖
🔘A feature is an element of something interesting or important.
🔜The number of parks is an important feature of the city.
It it also used as a general label for the parts of our faces.
🔘My big nose is my least favourite feature.
🔜When we want to say what is included in something, we use feature. Often it's important that they're there.
🔘This phone features an amazing camera.
🔜Just remember, we use the word feature to talk about interesting or important things.
#feature👨🏫@America
➖➖➖➖➖➖➖➖➖➖➖➖
🆕 Crypto News @Money
😁 Crypto Game @Egame
🇺🇸 US News @America
🇯🇵 Japan News @Japan
🇦🇪 UAE News @Dubai
▶️ Popular Movies @Videos
😜 Best Funny Video @Funnys
Grup ve kanallarda , 'Mesaj Sabitleme' ayrıcalığına sahip olan yöneticiler, 48 saatten daha eski olan iletileri düzenleyebilir:
Android ✅
Android X ✅
iOS ❌
Masaüstü ✅
macOS ✅
Webogram ❌
@Telegram#feature 02.03.2019
The last time we met
The last words you Said
were not just words ,
But bullets in my lungs .
These beautiful clouds and cold Wheather ,
Reminds me of the moments we spent together .
Celebrating first Eid in your absence ,
Makes me guilty for my existence.
Scrolling through my WhatsApp
these days,
feels that life has left me no ways
I always felt happy whenever we met ,
But now ,
Your name forces me to regret ,
Your wait compels me to forget ,
And , even your thoughts pierces my heart.
-CH.Irfan.
#review
#poem
#feature
It was 3am back then
I was laying on the bed
The Mullioned windows were open
The stars above in the night were gleaming
Suddenly onshore breeze had started
I turned off my phone and Started
Thinking of a dazzling Lady
I was devising a Scenario
of me and the graceful Lady
The scenario doesn't exist in real
But,
it gives peace In real
It gives me the Inner endearments
It gives a feeling that is forthcoming
I was fully Shifted to palace with her
That place was completely Magical
We were creating an album of Our life
And in an instant, it started Thundering
I Woke up from my pleasant Dream
The high wind started, The birds were
Moving from one tree to another
I closed my Windows
Gradually Heavy Downpour started
The Dream was left incomplete
But I made a Smile
And Thanked that period
For making me contented in
Today's Selfish World.
#review
#poem
#feature
The last time we met
The last words you Said
were not just words ,
But bullets in my lungs .
These beautiful clouds and cold Wheather ,
Reminds me of the moments we spent together .
Celebrating first Eid in your absence ,
Makes me guilty for my existence.
Scrolling through my WhatsApp
these days,
feels that life has left me no ways
I always felt happy whenever we met ,
But now ,
Your name forces me to regret ,
Your wait compels me to forget ,
And , even your thoughts pierces my heart.
-CH.Irfan.
#review
#poem
#feature
📱Figma AI orqali yangi featureʼni ishga tushirmoqda
Avtomatik o‘lchamni o‘zgartirish, tarjima qilish, variantlar yaratish, shriftlarni o‘zgartirish va bularning barchasi to‘g‘ridan-to‘g‘ri kanvasda bo‘lishi va’dasi berilmoqda.
Yangi featureʼlarni sinash uchun Alfa versiyasiga yozilmoqchiman. Agar qiziqarli narsa bo‘lsa, kanalimda yozaman.
@suxrobblog » #figma#feature#AI
🟢 Paynetdan rasmiy munosabat
...Boshqa ilovalarga oʻtishni hojati yoʻq. Boshqa dasturlarni mazasini qochiramiz! 😎 (deyaptilar, menimcha aka)
@suxrobblog » #paynet#feature
🟢Paynet uchun elektr limitini funksiyasini qo'shish uchun taklif dizayn
— Shunchaki, Paynetdan foydalanganim uchun taklif sifatida chizdim)
P.s. Dizayn paynet dasturining dizayn tizimiga asoslangan holda chizilgan. UI'dagi kamchiliklar ustida detalniy to'xtalmaganman.
#paynet#feature » @suxrobblog