Можно ли в 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
🌎 In the rainforests of Borneo, the rare "shy leaf" or Mimosa pudica folds its leaves instantly when touched! This unique plant movement helps deter hungry herbivores and even protect against harsh weather—a botanical marvel using touch as a survival tool. ✨
#botany⚡#rainforest⚡#adaptation
👉subscribe Interesting Planet
🌎 Deep in Madagascar’s rainforests grows the rare “suicide palm” (Tahina spectabilis). This palm lives for decades, then flowers only once, producing a massive cluster with millions of small blooms, before dying. Fewer than 100 adult plants have been recorded in the wild. ✨
#botany⚡#biodiversity⚡#rainforest
👉subscribe Interesting Planet
👉more Channels
🌎 The Australian native Anigozanthos, known as kangaroo paw, features velvety, tubular flowers shaped like a kangaroo's foot. Its unique structure attracts birds rather than insects for pollination. Some species display brilliant red, yellow, or green hues, and are found nowhere else in the wild. ✨
#botany⚡#biodiversity⚡#Australia
👉subscribe Interesting Planet
👉more Channels
On 3 December 1586, Sir Thomas Harriot introduced potatoes to England. He also sketched the moon through a telescope in July 1609, months before Galileo. 🥔🌕🔭
[Read more]
@googlefactss
#History#Science#Astronomy#Botany#Renaissance
🌎 The quiver tree, native to southern Africa, stores water in its trunk and branches, allowing it to thrive in scorching deserts and bloom spectacularly after rare rains. ✨
#botany⚡#adaptation⚡#Africa
👉subscribe Interesting Planet
🌎 The corpse flower (Amorphophallus titanum) from Indonesia produces one of the world’s largest and smelliest blooms, reaching over 3 meters tall. The flower emits a strong odor similar to rotting meat, which attracts carrion beetles and flies for pollination. ✨
#plants⚡#botany⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 The world’s smallest flowering plant, Wolffia globosa, floats on freshwater ponds and is less than 1 millimeter long. A single gram can contain over 150,000 individual plants. ✨
#plants⚡#biodiversity⚡#botany
👉subscribe Interesting Planet
👉more Channels
🌎 Hidden deep in Western Australia, the rare Kingia australis plant produces tall, grass-like stems crowned with spiky flower heads. Its slow-growing trunk can take up to 150 years to reach just 5 meters, making it one of the region’s botanical oddities. ✨
#plants⚡#botany⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 The Hydnora africana is a rare, parasitic plant native to southern Africa. It grows underground, emerging only to bloom with a fleshy, foul-smelling flower that attracts beetles for pollination. Its flowers can take up to a year to develop under the soil. ✨
#plants⚡#biodiversity⚡#botany
👉subscribe Interesting Planet
🌎 The Rafflesia arnoldii holds the record for the world’s largest single flower, measuring up to 1 meter across. This rare Southeast Asian plant emits a strong odor like rotting meat to attract pollinating flies, and it lacks leaves, stems, or roots of its own, living entirely as a parasite on vines. ✨
#plants⚡#botany⚡#biodiversity
👉subscribe Interesting Planet
🌎 In the Himalayan foothills, the Kalpavriksha, or “tree of heaven,” is a fig tree revered for living over 2,500 years. Its resilient roots stabilize soil and support hundreds of animal species, making it both a cultural icon and a pillar of its ecosystem. ✨
#botany⚡#longevity⚡#wildlife
👉subscribe Interesting Planet
🌎 The Welwitschia mirabilis plant of Namibia is one of the world’s oldest living plants, with some individuals estimated at over 1,500 years old. Its two long, ribbon-like leaves continually grow from the base and can reach more than 4 meters in length. ✨
#botany⚡#africa⚡#desert
👉subscribe Interesting Planet
👉more Channels