Можно ли в 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
On 'big-game hunters'
What if I tell you that one man formulated the whole of the folklore tradition of Stone Age big-game hunters -- hunting magic, initiation ceremonies, dancing shamans, pregnant horses, nubile naked women -- and even an art-historical development of imagery?
Your entire perception of the Paleolithic and Neolithic was defined by Abbé Breuil🔗, a Catholic priest in the early 20th century.
Of course, this -- reconstructing prehistory on the basis of contemporary behavior and thinking -- is exactly what should NOT be done. But Breuil did it.
The idea of "initiation ceremonies" was derived from one set of small heel prints, supposedly of children, in one alcove in one cave. This is the sort of single data point through which any number of lines could be graphed. It begged to be equated with initiation rites of contemporary primitives by anthropologists.
Overall there needs to be a re-evaluation of data, considering the developing consciousness of man.
#anthropology
@EuropeanTribalism
Anthropologist Madhumala Chattopadhyay, took part in the only successful, nonviolent expeditions to the Sentinel Islands, this is extremely rare given the islands’ usual hostility to outsiders.
She was the only woman to go along on such expeditions, where all other expeditions failed.
Contacting them is illegal, the community must be left alone.
For their safety.
[Read for yourself here]
@googlefactss#anthropology#sentinel
🌎 The San people of southern Africa tell legends of the /Kaggen, a trickster deity that often takes the form of a praying mantis. These stories, documented by 19th-century ethnographers, reflect the San’s deep connection to animals and the land. There are over 450 recorded San myths collected in the Bleek and Lloyd archive. ✨
#mythology⚡#Africa⚡#anthropology
👉subscribe Interesting Planet
👉more Channels
🌎 In Madagascar, the turning of the bones ceremony, or Famadihana, sees families exhume ancestors, rewrap the remains in fresh cloth, and dance with the bodies to live music. This ritual, held every seven years, honors lineage and strengthens family bonds. ✨
#traditions⚡#anthropology⚡#Madagascar
👉subscribe Interesting Planet
👉more Channels
🌎 For centuries, residents of Whittlesea, South Africa, have participated in the Intonjane ritual—a traditional female initiation ceremony. Young women undergo seclusion, teachings about adulthood, and symbolic rituals marking the transition to womanhood. Anthropologists report Intonjane is practiced mainly among Xhosa communities and usually lasts about a week. ✨
#culture⚡#traditions⚡#anthropology
👉subscribe Interesting Planet
👉more Channels
🌎 In Papua New Guinea, the Korowai people still build treehouses perched up to 35 meters above ground. This tradition began as a way to avoid floods, wild animals, and rival clans. Some Korowai treehouses even have separate “guest” platforms for visitors or ritual gatherings. ✨
#anthropology⚡#traditions⚡#rituals
👉subscribe Interesting Planet
👉more Channels
🌎 In Vanuatu, the Naghol or "land diving" ritual involves men jumping from tall wooden towers with vines tied to their ankles. This dangerous tradition, practiced on Pentecost Island, is meant to ensure a good yam harvest. Some platforms are over 20 meters high, and proper vine length is crucial to prevent injury. ✨
#traditions⚡#anthropology⚡#rituals
👉subscribe Interesting Planet
👉more Channels
🌎 In Indonesia’s Tana Toraja region, families celebrate Ma’nene, a ritual where they exhume deceased relatives, clean their bodies, and dress them in fresh clothes. This custom honors ancestors and reinforces family ties. Some mummies are carried through the village during the ceremony, which happens every few years. ✨
#tradition⚡#anthropology⚡#festival
👉subscribe Interesting Planet
👉more Channels
🌎 In Papua New Guinea, the Kaningara people of the Sepik River region perform a crocodile-scarification ritual. Teenage boys undergo elaborate skin-cutting ceremonies that create raised scars resembling crocodile scales, symbolizing a spiritual connection with the river’s sacred crocodiles. The process involves hundreds of cuts and can last several hours. ✨
#ritual⚡#anthropology⚡#tradition
👉subscribe Interesting Planet
👉more Channels
🌎 In the folklore of the Ainu people from Japan's Hokkaido region, the kamuy are powerful spirits thought to control natural forces like weather and animals. Early ethnographers documented dozens of distinct kamuy, each responsible for maintaining harmony between humans and the environment. ✨
#mythology⚡#cultures⚡#anthropology
👉subscribe Interesting Planet
👉more Channels
Igbo‑Ora, Nigeria — nicknamed the 'Twin Capital' — reports twin birth rates around 4–5% (~40–50 per 1,000), far above the global average (~1–1.5% or 10–15 per 1,000). Nearby Yoruba communities and parts of Benin show similar rates. (Figures approximate.)"
@googlefactss#Nigeria#anthropology#twins
🌎 In the Indonesian village of Trunyan, the dead are laid out on the ground and covered with bamboo cages instead of being buried. The local Taru Menyan tree releases a natural fragrance that masks odors, allowing bodies to decompose above ground without attracting scavengers. ✨
#rituals⚡#anthropology⚡#Indonesia
👉subscribe Interesting Planet
👉more Channels