Можно ли в 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
🇵🇰#Pakistan: At least seven people, including two policemen, were killed and more than 20 others injured in an explosion targeting a police vehicle in the Serai Naurang area of Lakki Marwat district, Khyber Pakhtunkhwa province.
According to local authorities, the blast occurred in a crowded market area during a routine police patrol, causing multiple civilian casualties and extensive damage to nearby shops and vehicles. The exact nature of the explosion remains under investigation. However, the attack follows a recurring pattern in the region of TTP (Tehrik-i-Taliban Pakistan) militants specifically targeting police and security force vehicles.
Meanwhile, roughly 30 km away, TTP militants blew up the Lora Fateh Khel bridge in Bannu district, effectively isolating multiple nearby areas. Just days earlier, another police checkpoint in the region was targeted in a suicide attack.
(via @TKCkhyber on X)
🇵🇰#Pakistan: Footage showing the Pakistani armed group Ittihad-ul-Mujahideen ambushing an armoured police vehicle in the Bannu District. After firing several magazines and rpg rounds in the armoured vehicle, the police officer inside is still alive.
The militants, after attempting to smash the window of the vehicle, force the person inside to open the door, shooting him point blank with a pistol.
(via @war_noir)
🇵🇰#Pakistan: A Tehrik-i-Taliban Pakistan (TTP) sniper records the moment when a police checkpoint gets blown up by militants in the Kamal Sar market area of Bajaur.
The second part of the video also shows the aftermath of the explosion.
🇵🇰#Pakistan: Footage released today by Baloch Liberation Army's media showing their militants attacking a Pakistani Army camp in the Kech region. The attack was recorded on March 29th of this year.
The militants used RPG rocket launchers and small arms fire to suppress and destroy the military outpost.
🇵🇰#Pakistan: Footage showing a militant from Tehrik-i-Taliban Pakistan ambushing a Pakistani Army convoy in Khyber Pakhtunkhwa using an SVD.
(via @war_noir)
🇵🇰#Pakistan: The Balochistan Liberation Army has released footage of its attack on a Pakistani military boat in the waters of Jiwani, Gwadar, where three soldiers were killed.
🇵🇰#Pakistan: Balochistan Liberation Army (BLA) militants have ambushed a Pakistani Coast Guard (PCG) patrol boat off the coast of Jiwani, Gwadar, killing three troops who were on board.
This would mark the first time that Pakistani forces have been targeted at sea within Balochistan. No footage of the attack has emerged yet, but BLA media outlets have published a statement claiming responsibility.
The attack was also confirmed by the Pakistani side.
🇵🇰#Pakistan: Footage released by BLA (Balochistan Liberation Front) showing it's militants ambushing Pakistani soldiers in Quetta, Balochistan.
(via @war_noir)
🇵🇰#Pakistan: A police vehicle was blown up by an IED (improvised explosive device) in Lakki Marwat, in the Khyber Pakhtunkhwa province of Pakistan.
The explosion injured four police officers who were inside the vehicle at the time. No group has claimed responsibility for the attack so far, although the area has been an active region for attacks by TTP (Tehreek-e-Taliban Pakistan) militants.
(📸 via @pakafghanmatter on X)
🇵🇰Pakistan arrests activists at Women's Day march
More than 30 people, including women, men and children, were detained during an International Women's Day march in Islamabad on March 8. Among those held was sociologist Mavra Bari, who described being kept in a cramped cell and said detainees were beaten. An AFP journalist observed those released bearing signs of physical ill-treatment.
Amnesty International and Human Rights Watch have documented a pattern of arbitrary detention, enforced disappearances and legal harassment of activists, lawyers and journalists in Pakistan. Human rights lawyer Imaan Mazari and her husband are serving lengthy jail terms for social media posts deemed anti-state, while digital journalist Sohrab Barkat has been held without trial since late 2025.
The Committee to Protect Journalists reported at least seven journalists killed in Pakistan in 2024, with others facing harassment. The Human Rights Commission of Pakistan's secretary general described new media laws as draconian, while press freedom group Reporters Without Borders has pointed to increasing state pressure on independent outlets.
#Pakistan
@asianomics
🇵🇰#Pakistan: The Balochistan Liberation Army (BLA) has launched a coordinated attack on a Pakistani Coast Guard post, killing three troops stationed there. From the footage, it seems that the soldiers were not armed during the attack.
The militants were allegedly "disguised" (possibly dressed as civilians or friendly troops). They passed through a Pakistani checkpoint on motorbikes before opening fire.
The footage was dated as March 15th and was posted on BLA telegram channels.