Можно ли в 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
“When they attacked some village, they called all the people to one place. ‘Everyone must follow us and our religion. If not, we must shoot you,’” says Khuseini from Nigeria about Boko Haram terrorists.
This criminal group is responsible for killing thousands of people. Khuseini and his family fled their hometown when Boko Haram arrived. Now he lives in the Dar es Salaam refugee camp and teaches Arabic to kids at the local school. Khuseini says the kids are deeply traumatised by the terrorists’ brutality. They remember how Boko Haram attacked their town, killing their friends. There are machine guns, blood, and killings even in kids’ drawings.
Today is Children’s Day in Nigeria. Watch the clip to see how kids – Boko Haram’s victims - live in the refugee camp and try to get back to everyday life. Then, find out more in our documentary Hot Spot Chad.
#crime
Follow: https://t.me/rtdocumentary
‘He’s not resisting arrest; he’s on the ground. You’ve him in handcuffs. Why is there a need to hit him in the back with a rifle?’ – asks a desperate mother whose child died due to police brutality. Quincy and his girlfriend argued, he left the house, leaving her angry. She called the police and told them he had a rifle. That fatal lie cost Quincy his life. Five police officers didn’t even intend to find out the truth but tackled and beat the young man to death.
Cases like this are common in the USA. Hundreds of people die every year at the hands of law enforcement officers. Watch the clip to see some cases. Do you think it’s possible to change the situation? See the documentary Once Upon A Crime to learn what people do to stop police brutality.
#crime
Follow: https://t.me/rtdocumentary
🎬 Adolescence
Gênero: #Crime, #Drama
⭐️ IMDb: 8.1
⏳ Duração: 15 Episódios
📝 Sinopse:
Quando um garoto de 13 anos é acusado do assassinato de um colega de classe, sua família, o terapeuta e o detetive responsável ficam perguntando o que realmente aconteceu.
Fonte: IMDb
🔵Inscreva-se em @Assistir
*Patrocinado: Anime Bot
🍿 'The Penguin': The Most Anticipated Spin-off of 'The Batman' 🎬
📆Premiere: September 19, 2024
🎭Genre: #Crime · #Drama
Colin Farrell dives into the role of Oz Cobb, aka The Penguin, in this series that promises to expand the universe of Matt Reeves' 'The Batman.' With 3.5 hours of daily makeup, Farrell transforms into Gotham's crime boss. The trailer, unveiled at Comic-Con, left everyone in awe. 🎥
The interesting part is how Reeves initially planned a series for DC, and HBO finally made it happen. Cristin Milioti and Rhenzy Feliz join Farrell in an impressive cast. And watch out! The Penguin will return in 'The Batman II' in 2026. 🦇✨
🍿The Penguin: Colin Farrell Returns to Gotham
📆Release: Fall 2024
🎭Genre: #Crime · #Drama
The new trailer for 'The Penguin' brings Colin Farrell back as Gotham's infamous gangster, Oswald Cobblepot. This spin-off from Matt Reeves' 'The Batman' follows Cobblepot's rise to power after the death of Carmine Falcone. 🚦🔫
What's really fascinating is how Farrell's makeup has evolved, giving him an even more menacing look true to the iconic DC villain. Plus, the brewing tension with Sofia Falcone, played by Cristin Milioti, promises electrifying drama. Don't miss this thriller, which is already shaping up to be a hit. 🌆🔥
> 𝘴𝘦𝘳𝘪𝘦𝘴 · 🚀𝘣𝘰𝘰𝘴𝘵