Можно ли в 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
Sunday's countrywide vote will lead to the selection of 4,500 local projects that will be assigned US $10,000 each. Local organizations have held assemblies to identify the most pressing needs for communities.
Read the full story here: https://venezuelanalysis.com/news/venezuela-national-popular-consultation-sees-voters-choose-state-funded-projects/
#Venezuela#Communes#PopularPower
Robert Longa, a key cadre from El Panal Commune, discusses US interventionism and Venezuela’s participative and protagonistic democracy.
Read the interview: https://venezuelanalysis.com/interviews/on-elections-and-collective-emancipation-a-conversation-with-robert-longa/
#Venezuela#Democracy#PopularPower
🆕 NEWS | Venezuelans Vote in Third ‘National Popular Consultation’ to Select State-Funded Projects
🇻🇪 The grassroots electoral process was held in 5,334 communal circuits, where voters chose from over 36,600 proposals. Winning initiatives will receive USD 10,000 and be executed by grassroots collectives. The consultation is the first of six planned for 2025.
🔗 Read the full report here: https://shorturl.at/S90an
#Communes#NationalPopularConsultation#PopularPower
With today's electoral process winding down, VA's Cira Pascual Marquina files this report from the combative, working-class barrio 23 de Enero in western Caracas. Participation, as always in this Chavista bastion, has been positive throughout the day.
#Venezuela#PopularPower#LocalElections
🆕 NEWS | Maduro Presents Constitutional Reforms Package to Amplify Democracy and Chart ‘Sustainable’ Economic Course
President Nicolás Maduro has introduced an 80-article constitutional reform proposal, emphasizing participatory democracy and a long-term economic roadmap.
A National Commission has been formed to lead the process, and a public consultation will take place before a national referendum. A final proposal is expected in 90 days.
🔗 Read the full report here: https://shorturl.at/IVq9h
#Constitution#NicolasMaduro#PopularPower
🎙️ Episode 39 of the VA Podcast is out now!
This episode examines the role of Venezuelan communes in socialist construction and anti-imperialist struggle, with guests Chris Gilbert and Cira Pascual Marquina.
Both were guest editors of Monthly Review's latest issue, "Communes in Socialist Construction". The conversation covers the meaning of communes, Marx’s theory of the commune, and the political relevance of the slogan “Commune or Nothing!”
🎧 Watch here: https://youtu.be/u0RyfxgQgfc
#Communes#PopularPower#VAPodcast#AntiImperialism#Venezuela
Upcoming Elections in Venezuela: On Dec. 15, more than 4,000 communal circuits nationwide will host elections to select 30,000 peace judges. These officials, chosen through popular vote, will mediate community disputes and address local governance issues under newly reformed laws.
Over 4,817 polling centers have been set up, and candidates present their plans in community assemblies and door-to-door campaigns. This initiative is part of Venezuela's broader efforts to advance grassroots democracy and participatory governance.
Read the full report here: https://venezuelanalysis.com/news/venezuela-prepares-for-election-to-select-local-peace-judges/
#elections#participatorydemocracy#popularpower#communes
🗒️🗣️ INTERVIEW | Heyerde López: ‘Our Challenge Is Staying True as a Left-Wing Organization’
In the latest VA interview, activist Heyerde López reflects on the structural challenges facing grassroots organizing in Venezuela, pointing to the difficulty of sustaining long-term projects while maintaining political coherence. López, a member of "Fundación Nativa Crea" in Guarenas, frames this as a central tension: “The main challenge is staying true to our identity as a left-wing organization,” he says, highlighting mounting economic pressures and contradictions in the relationship between popular power initiatives and state institutions.
US sanctions and restrictions on wheat imports forced the closure of the group’s community bakery and café, key nodes in its local production network. The experience underscores how external constraints continue to impact grassroots economic initiatives. The collective is now working to relaunch these projects, with an emphasis on rebuilding communal forms of production and strengthening local productive capacity.
Despite these setbacks, "Fundación Nativa Crea" remains embedded in broader networks of communes and social movements, while expanding its work in political education, communications, and grassroots production.
Read the full interview here 👉https://venezuelanalysis.com/interviews/heyerde-lopez-our-challenge-is-staying-true-as-a-left-wing-organization/
#Art#Communes#NationalPopularConsultation#PopularPower
📝 INTERVIEW | Building Communal Power from the Mayor’s Office: A Conversation with Lisbed Carolina Parada
With municipal elections scheduled for Sunday, July 27, VA interviewed Lisbed Carolina Parada, mayoral candidate in the town of Urachiche, Yaracuy state.
A longtime communal activist, Parada discussed the need to put institutional spaces at the service of popular power in the territories.
Follow the link to read the interview: https://venezuelanalysis.com/interviews/building-communal-power-from-the-mayors-office-a-conversation-with-lisbed-carolina-parada/
#MunicipalElections#PopularPower#Urachiche#Communes
📰 NEWS | Venezuela: Popular Organizations Push Direct Distribution Routes to Boost Food Security
Pueblo a Pueblo and the Communard Union are providing affordable access to fish and vegetables by connecting popular organizations. Pueblo a Pueblo delivered 1,000 packs of fish and seafood, each weighing 3.8 kilograms, in Caracas, Yaracuy, Lara and Trujillo. The packages, sold at $13, represented savings of 50–60% compared to local markets.
At the same time, the Communard Union transported 3.5 tons of vegetables from Trujillo to communes in Lara state. Between 500 and 600 people purchased potatoes, carrots, onions and tomatoes at prices around 40% below market levels. Both initiatives strengthen direct distribution routes between producers and communities.
🔗 Read the full report: https://shorturl.at/3HDgP
#CommunardUnion#FoodSovereignty#PopularPower#PuebloaPueblo
🖊 COLUMN | Venezuela, Popular Power and Coffee
Jessica Dos Santos' latest column showcases how 18 communes in Sanare, Venezuela, launched the “Enriquito Colmenárez” coffee-roasting plant after receiving it from the Agriculture Ministry.
The grassroots initiative supports campesinos with subsidies, training, and direct diesel access, while preparing to export robusta beans to the US and Russia. The plant will also host a soil lab through a partnership with the United Nations Food and Agriculture Organization (FAO).
🔗 Read the full VA column here: https://shorturl.at/EAU4t
#Coffee#Peasants#Campesinos#PopularPower#TalesofResistance