Можно ли в 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
I present a soft, relaxed, cozy, warm soul (and body 😉) plaid shirt.
Autumn is coming 🍂 and we will all need it paired with denim, leather jackets and trench coats soon. And for those who can't wait - try to style with summer cotton skirts, one love 💕
#inspirationINVOGA
🌺 Flowers always, 🌼 flowers everywhere!
🌺Flower Like:
- choker
- belt (I liked it very much 👌🏼 - as an alternative to a choker)
- brooch
🌸Flower on:
- shoes
- swimsuit
- shirt
#inspirationINVOGA
TOP 5 ideal neighbors for metallic trousers:
1. White T-shirt
2. Black/white tank top
3. Basic jersey
4. Masculine shirt or jacket
5. Classic longsleeve
Shine with pleasure and let the whole world be reflected in your pants - no matter how it sounds😂
#inspirationINVOGA
There are five must-have accessories for the upcoming (and for someone have already come) cold weather:
1. Voluminous long scarf
2. Bib
3. Short or long gloves
4. Puffy/quilted bag
5. Balaclava
#inspirationINVOGA
Let's look at the beauty celebration from Prada about the new fragrance PARADOXE
Here we have everything in style:
conciseness in color and silhouettes;
oversized jackets
socks
a drop (or not a drop) of glitter and a few feathers
leather
crossbody with very short straps
And triangles, triangles, triangles😊
#inspirationINVOGA
Hoodie + Coat - Yes or No?
As for me, there is nothing better and more convenient than such a couple for daily routine worries that have to be done more often than bright events happen😉🤷🏼♀️
While it is still not too cold, the coat can be left open. The hoodie can be worn without an underlayer. However, it is also not forbidden to pry off the turtleneck to save the throat and tighten the belt on the coat.
#inspirationINVOGA
A bit of street style from Paris Fashion Week Spring 2023:
- total denim, asymmetric denim, double waist,
- loose knit jersey,
- bomber jackets, leather coats, and trench coats,
- fit and transparency,
- balaclavas,
- over-the-knee boots and high boots
#inspirationINVOGA
☕️It's cloudy and rainy outside the window☔️. The mood is to wrap yourself in a knitted dress and enjoy your favorite cappuccio - what could be better for a Wednesday morning?
Favorite🏆 styles:
1. Knitted dress with sneakers
2. Knitted dress with trumpet/jockey boots that overlap with the dress.
3. Knitted dress overskirt
4. Knitted dress with rough, worn leather
#inspirationINVOGA
I went to Etro Spring 2023 street style for paints, prints, and textures, sharing the mood I caught there and photos made by my own hands 🤲🏼
I’ll start with the atmosphere, the show, and as a result, the street style took place in the industrial zone of Milan and was accompanied by a roar, howl, and signals of disgruntled trucks 🚚🚛 , traffic that was not blocked, but photographers and street stylers scurrying everywhere and everywhere, significantly complicated it 🔴
And then everything is as expected - notes of ethnicity in the form of jersey with fringes, small and complex prints, bright saturated colors, patchwork, some leather, but more suede.
I have loved Etro for many years and have chosen the perfect accents for my wardrobe there! ❤️🤎
#inspirationINVOGA
In the meantime, Milan is taking over the baton of Fashion week, in which I am also going to participate and share with you. We review and study London street style.
Lots of ruffles and frills, puffed sleeves and huge collars, brocade and tulle combined with a bit of English stiffness, plaid, lots of Mary Jane variations, golfs, leather, and punk casualness 🎸🤘🏼
#inspirationINVOGA
Who has butterflies in their stomach? 🦋😉 Release! This summer, and next fall, you can definitely👌🏼
We are not limited to flowers, we add butterflies in all dimensions - tops, jewelry, bags, belts, shoes, and when autumn comes, it will come to jackets.
Catch it while the season and treat with care😉
#inspirationINVOGA