Можно ли в 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
An #FBI Boston investigation has resulted in charges against 30 individuals for their roles in a global insider trading scheme that netted tens of millions in illicit profits.
The #FBI executed arrests in AL, CA, FL, NJ, and NY today for individuals who are accused of capitalizing on confidential information stolen from leading corporate law firms advising on mergers & acquisitions in Massachusetts and elsewhere.
Two subjects, located in Israel and Russia, are actively being sought.
1:11 PM · May 6, 2026
X LINK
Read more about today's takedown: https://ow.ly/tyCh50YVHRu
Now do CONGRESS...
Excongresista y lobista estadounidense condenado por actuar como agente no registrado de Venezuela en relación con un contrato de 50 millones de dólares.
Un jurado federal en Miami declaró culpable al excongresista estadounidense David Rivera de ejercer presión en secreto en nombre del gobierno venezolano y de lavar millones de dólares vinculados a ese trabajo, en violación de la Ley de Registro de Agentes Extranjeros.
Obtenga más información sobre la investigación realizada por #FBI y nuestros socios encargados de hacer cumplir la ley:
https://www.justice.gov/usao-sdfl/pr/former-us-congressman-and-lobbyist-convicted-acting-unregistered-agents-venezuela
Panic and protests at the #FBI😮
“According to an email from acting Director Brian Driscoll and reviewed by The Gateway Pundit, each field office is required to submit a list of all personnel, current and former, who were involved in January 6th investigations/prosecutions by noon on Tuesday, February 4th.”
Politics, retribution behind FBI purge, agents allege in new lawsuit against Patel, Bondi
Three senior FBI officials who were abruptly fired last month by Kash Patel, the FBI director, are claiming in a new lawsuit against the Trump administration that they were illegally terminated at the direction of the White House for purely political reasons.
The complaint, filed in U.S. District Court in Washington, D.C., Wednesday, alleges Patel told one of the agents that his job as FBI director depended on firing agents involved in past investigations of President Trump.
Patel allegedly said "he had to fire the people his superiors told him to fire, because his ability to keep his own job depended on the removal of the agents who worked on cases involving the President," the lawsuit alleges.
"Patel explained that there was nothing [anyone] could do to stop these or any other firings, because 'the FBI tried to put the President in jail and he hasn't forgotten it,'" the complaint claims. According to the complaint, former FBI agent Brian Driscoll indicated he believed Patel was referring to his superiors at the White House and the Justice Department which "Patel did not deny."
#Trump#FBI
👂More on Trump's Ear ⚠️
🔍🏛️EXCLUSIVE: FBI DIVERTS 25% OF AGENTS TO IMMIGRATION — CHILD CRIMES LEFT UNDERSTAFFED
🔹 Over six thousand FBI agents (quarter of all staff) reassigned to immigration cases in Trump's first 9 months 👮
🔹 Massive 23X increase from previous levels — agents pulled from child exploitation, terrorism, corporate fraud 🚨
🔹 ICE death toll hits 18 in 2026 as Cuban immigrant dies in Georgia detention — suspected suicide 💀
🔹 Federal charges filed against Salvadoran man shot by ICE in California traffic stop gone wrong 🚔
When immigration becomes top priority, who's protecting kids from predators? Priorities matter 🔥⚖️
#Immigration#FBI
@america