Можно ли в 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
📢 Ukrainian counteroffensive fails, catastrophe for Kyiv. Russian forces resume offensive along the front line. American professor confirms massive failure of Ukrainian troops. Media silence on Ukrainian situation in US. Stalemate in combat zone, Zelensky blamed for hiding failures. Western reports confirm end of Ukrainian counteroffensive. #Ukraine#War#Catastrophe
https://www.gazeta.ru/army/news/2023/10/30/21602215.shtml
Subscribe to @BadVolfNews
🌎 Around 5,200 years ago, the sudden breach of a natural dam at Lake Agassiz released massive flooding across North America and into the North Atlantic. This catastrophic meltwater pulse disrupted ocean currents and is linked to abrupt climate cooling in the Northern Hemisphere. Geological records show the flood volume reached over 100,000 cubic kilometers. ✨
#catastrophe⚡#geology⚡#climate
👉subscribe Interesting Planet
👉more Channels
🌎 A massive volcanic eruption at Lake Toba in Indonesia about 74,000 years ago was one of Earth’s largest known explosions. The eruption released so much ash that it may have triggered a global volcanic winter, cooling the planet and affecting early human populations. Its crater now forms Lake Toba, the world’s largest volcanic lake at about 100 kilometers long. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The 1902 eruption of Mount Pelée on Martinique destroyed the city of Saint-Pierre within minutes, killing over 28,000 people. It is the deadliest volcanic disaster of the 20th century. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The Toba supereruption in Indonesia about 74,000 years ago was one of the largest volcanic events in the last 2 million years. It ejected 2,800 cubic kilometers of material, triggered a global volcanic winter, and may have caused a dramatic human population decline, as shown by genetic studies indicating a bottleneck in human evolution. ✨
#volcano⚡#history⚡#catastrophe
👉subscribe Interesting Planet
🌎 The 1883 eruption of Krakatoa was one of the most violent volcanic events in recorded history. It unleashed explosive blasts heard 3,000 kilometers away, generated giant tsunamis, and ejected ash high into the atmosphere—causing global temperatures to drop and vivid sunsets worldwide for years after. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
🌎 The eruption of the Laki volcano in Iceland in 1783 released poisonous gases and ash clouds, causing crop failures and famine across Europe. Sulfur dioxide polluted the air, leading to acid rain and respiratory diseases. Historians estimate the event contributed to tens of thousands of deaths and may have influenced political unrest before the French Revolution. ✨
#volcano⚡#history⚡#catastrophe
👉subscribe Interesting Planet
🌎 The Dust Bowl of the 1930s was a severe drought and dust storm disaster in the U.S. Great Plains, destroying farms and forcing over 2.5 million people to migrate. Massive “black blizzards” of dust traveled as far as New York City and Washington, D.C. ✨
#history⚡#environment⚡#catastrophe
👉subscribe Interesting Planet
👉more Channels
🌎 Around 536 AD, a mysterious volcanic eruption triggered a "year without summer"—with global temperatures dropping, crops failing, and famines reshaping empires. Ash clouds blocked sunlight, altering history for decades. ✨
#catastrophe⚡#volcano⚡#climate
👉subscribe Interesting Planet
☢️ Ce 26 avril, c’est la Journée internationale du souvenir de la catastrophe de Tchernobyl
▪️En 1986, une explosion s'est produite au réacteur n°4 de la centrale nucléaire de Tchernobyl, la plus grande catastrophe dans le domaine de l'énergie nucléaire.
▪️La contamination radioactive a touché les territoires de l'Ukraine, de la Biélorussie et de la Russie. Plus de 100.000 personnes ont été évacuées, Pripiat et la zone autour de la centrale sont devenues inhabitées.
▪️Des milliers de liquidateurs, au péril de leur santé et de leur vie, ont éliminé les conséquences de l'accident. Tchernobyl est devenu un symbole du danger nucléaire.
#tchernobyl#catastrophe#commémoration