Можно ли в 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
🧭January 29 marks theDiscoverers’ Day in Russia
🧊 On this day in 1820, Russian naval officers Faddey Bellingshausen and Mikhail Lazarev discovered #Antarctica – the sixth continent.
The expedition lasted 751 days. Sailing aboard the two sloops Vostok and Mirny, the 102-strong crew were the first to map the boundaries of the Antarctic continent.
The voyage was extremely arduous and dangerous. Small wooden sailing vessels had to navigate close to ice and icebergs, often in dense fog. Heading south, on January 28, the Russian navigators came within close proximity of the icy shores of a previously unknown land.
📝Mikhail Lazarev later wrote about that historic moment:
“We reached latitude 69°23 S, where we met main ice of extraordinary height… and looking out from the crosstrees, it stretched just as far as our gaze could reach… At last, there lay before us that southern main, so long sought after, whose existence scholars in their studies had deemed necessary for the balance of the globe.”
Braving fierce ocean swells and polar ice, the expedition successfully circumnavigated the continent. This remarkable voyage brought glory to Russia and turned St Petersburg into a leading centre of global geography. The results of the expedition, which led to the discovery of Antarctica and twenty-nine new islands, represent an Russia's outstanding contribution to the history of geographical exploration.
Later, shortly after the end of the Great Patriotic War, the Soviet Union resumed its exploration of the continent. In 1946, the Slava whaling flotilla, carrying a scientific team, sailed to Antarctica. They reached the point where Bellingshausen and Lazarev had sighted the “main ice” and verified the accuracy of their original accounts.
On February 13, 1956, the first Soviet Antarctic research station, the Mirny Observatory, was officially opened. This was later followed by a network of year-round Russian stations.
🇷🇺 Today, Russia continues its research in Antarctica. In late 2024, a new wintering complex entered service at the inland Vostok Station. In 2025, the research vessel Akademik Tryoshnikov completed the International Antarctic Coastal Circumnavigation Expedition. The 71st Russian Antarctic Expedition is currently underway.
Antarctica🇦🇶
An eco-camp inspired by the space exploration era, providing exclusive access to the most remote locations on the continent.
Equipped with six heated pod rooms featuring floor-to-ceiling panoramic windows.
#Antarctica
@voyage
No man’s land
#video#Antarctica
It’s open to everybody and no country owns it. People and wildlife coexist here peacefully. What’s this wonderful place? It’s Antarctica, the world’s coldest and most pristine continent!
On this day, exactly 62 years ago, a conference in Washington DC paved the way for the Antarctic Treaty, which proclaims that the world's southernmost continent should be free of weapons, borders, and exploitation. Only science and collaboration are welcome here.
To honour that date, here are some interesting facts.
❄️ You can’t take anything out of the continent, including stones, feathers, or anything manmade.
❄️ Antarctica has the lowest recorded temperature on earth, -89.2 degrees Celsius.
❄️ America’s McMurdo station is the largest research station here, with over 1,000 scientists working throughout the year.
Follow: https://t.me/rtdocumentary
Antarctica 88
🆕Обновление
Вы попадётев Антарктиду, где сможете окунуться в жуткую научно-фантастическую историю. Готовы ли вы к встрече с ужасными существами, которых скрывает Антарктида?
⚙️Полная купленная Pro версия (299₽). Мод меню: разблокирован весь платный контент и другое. #Хорроры
#Хорроры@pm_plus
#Antarctica@pm_plus
📱Play Market +
⚡️ НАШ ЧАТ
🌎 Antarctic icefish stand out for surviving in freezing waters thanks to "antifreeze proteins" in their blood. These proteins prevent ice crystals from forming inside their bodies, letting them live where most fish would freeze solid. Some species have completely lost red blood cells and hemoglobin. ✨
#adaptation⚡#animals⚡#antarctica
👉subscribe Interesting Planet
👉more Channels
🌎 The deepest point on land is the Bentley Subglacial Trench in Antarctica, buried beneath almost 3 kilometers of ice. This hidden valley lies 2,555 meters below sea level, far deeper than Death Valley, and remains inaccessible except through advanced radar technology. ✨
#Antarctica⚡#geology⚡#extremes
👉subscribe Interesting Planet
🌍 Mount Erebus in Antarctica is one of the world’s southernmost active volcanoes. Its lava lake stays liquid year-round, despite harsh temperatures that often plunge far below freezing. ✨
#volcanoes⚡#Antarctica⚡#mountains⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Antarctica is the only continent entirely surrounded by ocean and is nearly twice the size of Australia. Its thick ice reflects sunlight, helping regulate Earth’s overall temperature. ✨
#continents⚡#oceans⚡#Antarctica⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌎 Beneath the Ross Ice Shelf in Antarctica, researchers discovered a thriving community of tiny amphipod crustaceans living over 500 meters below the ice. Scientists accessed this hidden ecosystem in 2015 by drilling through the thick ice, revealing life where sunlight never reaches. This shelf covers an area roughly the size of France. ✨
#ocean⚡#Antarctica⚡#crustaceans
👉subscribe Interesting Planet
👉more Channels
🌍 Antarctica is home to “blue ice” areas where strong winds strip away snow and expose centuries-old glacier ice, creating shimmering fields that reflect nearly as much sunlight as fresh snow. ✨
#glaciers⚡#Antarctica⚡#polar⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels