Можно ли в 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
🎥 VA’s Cira Pascual Marquina reports from Caracas' El Panal Commune in the 23 de Enero neighborhood, where participation has been high and people are praising the efficient voting process.
#LegislativeRegionalElections2025
🎥 "Let’s not leave spaces for those who once used the National Assembly to ask for sanctions to generate suffering and migration."
ALBA-TCP Secretary General Jorge Arreaza from the Manuel Palacios Fajardo polling station in El Panal Commune. This is where Hugo Chávez voted.
#LegislativeRegionalElections2025
🎥 VA’s Katrina Kozarek reports from Lara’s Communal Power Center, where voting began smoothly and locals await GPP candidate Luis Reyes Reyes.
#LegislativeRegionalElections2025
🎥 Voting underway in Caracas’ El Valle neighborhood. VA’s Ricardo Vaz reports from the ground as turnout emerges as the key factor in today’s legislative and regional elections.
#LegislativeRegionalElections2025
🗳️🇻🇪 ELECTIONS | Venezuela’s legislative and regional elections are underway. Electoral authorities report that 100% of voting station officials are present and 95% of polling booths were activated by 8:30 AM.
Nearly 16,000 polling stations have been set up across the country.
📡 Follow Venezuelanalysis’ rolling blog for live coverage throughout the day: https://venezuelanalysis.com/news/venezuelas-2025-legislative-and-regional-elections-rolling-coverage/
#LegislativeRegionalElections2025
📢 Venezuela heads to the polls today, May 25, to elect a new National Assembly, state governors, and regional legislative councils.
The United Socialist Party (PSUV) and its allies in the Great Patriotic Pole selected candidates through a hybrid process: grassroots assemblies across the country and leadership evaluations, according to PSUV candidate Oliver Rivas.
A total of 36 national parties, 10 regional ones, and 6 indigenous organizations are on the ballot.
🗳️ Follow Venezuelanalysis for rolling coverage throughout the day here: https://venezuelanalysis.com/news/venezuelas-2025-legislative-and-regional-elections-rolling-coverage/
#LegislativeRegionalElections2025
🗳️🇻🇪 This Sunday, Venezuelans return to the ballot box to choose new regional lawmakers and local officials.
Count on Venezuelanalysis for on-the-ground updates, context, and full election day coverage!
👉 In the meantime, check out our complete electoral guide here: https://shorturl.at/NylSl
#LegislativeRegionalElections2025
📘 GUIDE | Venezuela’s 2025 Legislative and Regional Elections: A Quick Guide
🗳️🇻🇪 Venezuelans head to the polls on Sunday, May 25, to elect a new National Assembly, governors in all 24 states, and members of regional legislative councils. This marks the 32nd electoral process under the Bolivarian Revolution.
Our quick guide breaks down the key elements of the vote, including the electoral process, major parties and candidates, and key races to watch.
👉 Read the full guide here: https://venezuelanalysis.com/analysis/venezuelas-2025-legislative-and-regional-elections-a-quick-guide/
#LegislativeRegionalElections2025
📰 NEWS | Venezuelan Electoral Authorities Run Election Exercise as Regional, Legislative Campaigns Enter Home Stretch
Venezuela’s National Electoral Council (CNE) carried out a nationwide voting simulation on May 10 in preparation for the May 25 elections, where over 21 million people are eligible to elect 285 National Assembly deputies and 24 governors.
CNE Vice President Carlos Quintero said the trial confirmed electoral readiness, with fewer than 2% of voting machines experiencing issues.
Meanwhile, the opposition is split between those campaigning and others, led by María Corina Machado, calling for a boycott. 36 parties are on the ballot, 13 of them allied with the ruling PSUV.
🗞 Read the full report here: https://shorturl.at/NhJ9l
#LegislativeRegionalElections2025
🎥 VIDEO | Maduro-led Forces Sweep Elections While US Silent: Discussion With Eyewitnesses
Venezuela held elections on May 25 that saw the pro-government Great Patriotic Pole secure overwhelming majorities both in the National Assembly and regional governorships.
In response, the International Manifesto Group convened a panel of international analysts to assess the electoral process, Venezuela’s internal political dynamics, and the broader geopolitical implications.
👉 Watch the full video here: https://venezuelanalysis.com/video/maduro-led-forces-sweep-elections-while-us-silent-discussion-with-eyewitnesses/
#LegislativeRegionalElections2025#NicolasMaduro
📝 INTERVIEW | Venezuela’s Participatory Democracy and the Struggle Against Imperialism: A Conversation with Alison Bodine
In the latest VA interview, international observer and activist Alison Bodine shares her reflections on Venezuela’s May 25 elections. She highlights the country’s participatory democracy, where political engagement goes far beyond the ballot box.
Bodine also critiques the role of mainstream media and calls for coordinated international solidarity to confront US and Canadian sanctions. “Seeing the Bolivarian Revolution in action has profoundly shaped my political views,” she states.
🔗 Read the full interview here: https://venezuelanalysis.com/interviews/venezuelas-participatory-democracy-and-the-struggle-against-imperialism-a-conversation-with-alison-bodine/
#LegislativeRegionalElections2025#Sanctions#Solidarity
📰NEWS | Venezuelan Government Denounces ‘Terrorist’ Plot to Sabotage May 25 Elections
Venezuelan authorities have detained 38 individuals—21 Venezuelans and 17 foreigners—accused of involvement in an alleged far-right conspiracy to sabotage the May 25 regional and legislative elections. Targets reportedly included embassies, hospitals, police stations, and public infrastructure.
According to Interior Minister Diosdado Cabello, the detainees included mercenaries and explosives experts who entered Venezuela via Colombia, posing as tourists. In response, flights from Colombia have been suspended until May 26 at 6:00 p.m.
🔗 Read the full article here: https://shorturl.at/UZMnJ
#LegislativeRegionalElections2025#Terrorism