Можно ли в 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
Seville, #Spain
Metropol Parasol (the Metropol umbrella, Spanish The Metropol Parasol, also known as the Mushrooms of Seville, is a concrete and wooden structure located in the Plaza de la Encarnacion. Plaza de la Encarnación) in the old quarter of Seville. The building was designed by German architect Jürgen Mayer, and construction was completed in April 2011. The 28-meter-high facility covers an area of 150 by 75 meters and claims to be the largest wooden structure in the world.
Fuerteventure, #Spain🇪🇸
This wonderful natural pool is located on the island of Fuerteventure. 🏝
Interestingly, Fuertever is considered one of the oldest islands of Spain, formed thanks to the eruption of the volcano more than 20 million years ago. This fact confirms the unusual form of the island and the complete absence of snakes and insects dangerous for humans. Also, the pluses of this place should include an almost complete absence of rains and a soft climate.
🇪🇸#Spain / Catalonia: There were intense clashes yesterday in Sentmenat (Barcelona) between anti-fascist protesters and riot police.
Groups of demonstrators took to the streets to oppose the opening of a new delegation and headquarters by the neo-Nazi group Núcleo Nacional. Hundreds of anti-fascist activists gathered near the industrial area where the far-right group was holding an event, leading to police charges as officers attempted to prevent protesters from reaching the venue.
(📹 via @rebonico on X)
🇪🇸#Spain: Europol and the Spanish National Police have uncovered a far-right accelerationist cell linked to The Base. Three suspects were arrested during coordinated raids in Madrid, Valencia and Castellón, with officers seizing firearms, ammunition, knives, tactical gear, and accelerationist/neo-Nazi propaganda.
According to investigators, the cell was "highly radicalised" and it had conducted paramilitary style training, while being allegedly in contact with The Base's founder, Rinaldo Nazzaro. Only a month ago, The Base issued messages on its Telegram channels urging the consolidation of its dispersed international cells.
(via The Guardian)
😍When talking about Barcelona, one immediately thinks of the Sagrada Familia.
📏
📏
📏
📏
📏
📏
📏
📏
After 137 years, this landmark has become one of the most visited not only in Catalonia but in all of Europe.
🌟
📏
📏
📏
📏
📏
📏
📏
📏
#Spain🇪🇸
@voyage
🗺Spain 🇪🇸
📏
📏
📏
📏
📏
📏
📏
📏
Mount Tibidabo — the highest point in the Spanish city of Barcelona, part of the Collserola range.
📏
📏
📏
📏
📏
📏
📏
📏
🌟From this hill, you get a stunning panorama of the Catalonian capital, enjoyed by both tourists and locals. Though relatively low at just over 500 meters above sea level, both the mountain and its summit attractions are visible from anywhere in the city.
📏
📏
📏
📏
📏
📏
📏
📏
#Spain
@voyage
November in Barcelona is pure magic
✨
📏
📏
📏
📏
📏
📏
📏
📏
💚This area between Urquinaona Square and Paseo de San Juan Avenue is a treasure trove of architectural masterpieces! Every building here is a work of art, rich in history and unique charm.
📏
📏
📏
📏
📏
📏
📏
📏
💚Imagine walking down a narrow street, the autumn leaves rustling underfoot, with majestic buildings towering around you, adorned with elegant balconies and carved doors. Time seems to slow down, and you’re immersed in the atmosphere of old Barcelona.
📏
📏
📏
📏
📏
📏
📏
📏
#Spain🇪🇸
@voyage
Spain 🇪🇸
Mount Tibidabo — the highest point in the Spanish city of Barcelona, part of the Collserola range.
From this hill, you get a stunning panorama of the Catalonian capital, enjoyed by both tourists and locals. Though relatively low at just over 500 meters above sea level, both the mountain and its summit attractions are visible from anywhere in the city.
#Spain
@voyage