Можно ли в 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
🎥 VIDEO | Through the "National Popular Consultation", communities nationwide are directly managing resources and shaping local development.
🇻🇪🗳️ In the latest consultation, over 5,000 communal circuits and communes took part, selecting priority projects in water, healthcare, and infrastructure. Watch the video to learn more!
#Communes
🗣 INTERVIEW | In Venezuela, the Commune Is Not Just a Utopia: A Conversation with Cira Pascual Marquina
Cira Pascual Marquina discusses the Commune as both the path and end-goal of Venezuela's socialist project, highlighting the importance of communal organization in overcoming capitalist structures and building a more democratic society.
🔗 Read the full interview here: https://venezuelanalysis.com/opinion/in-venezuela-the-commune-is-not-just-a-utopia-a-conversation-with-cira-pascual-marquina/
#Communes
🎥 MULTIMEDIA | Renewed ‘Maximum Pressure Campaign’ on Venezuela: Challenges and Resistance
📢 The Venezuela Solidarity Network (VSN) held a webinar addressing the U.S. government’s renewed “maximum pressure” campaign against Venezuela. Researcher Yosmer Arellán and Venezuelanalysis member Cira Pascual Marquina spoke on the impact of intensified sanctions and the grassroots resistance underway.
🔗 Don’t miss the full webinar here: https://shorturl.at/Suhd6
#communes#sanctions#USVenezuelaRelations
📰 NEWS | Maduro Marches with Communal Youth Ahead of Popular Consultation as Trump Considers Venezuela Land Strikes
Venezuelan President Nicolás Maduro marched with thousands of members of the Communal Youth Committees in western Caracas ahead of the Nov. 23 popular consultation. Communities will choose local initiatives that receive state funding, marking the fourth consultation this year as the government reports 4,000 officially registered communes.
At the same time, senior US military and intelligence officials have presented Trump with updated options for possible operations in Venezuela. The USS Gerald R. Ford Carrier Strike Group has entered the US Southern Command’s area, joining additional warships, a nuclear submarine and around 10,000 troops deployed since August.
International scrutiny has intensified. CELAC–EU leaders called for respect for international law, while UN High Commissioner for Human Rights Volker Türk condemned recent US maritime strikes that have killed at least 80 people.
Read the full report here 👉🏾https://shorturl.at/YgVUh
#Communes#NicolasMaduro#USVenezuelaRelations
📑🖊 OPINION | ‘Neoliberal and Authoritarian’? A Simplistic Analysis of the Maduro Government that Leaves Much Unsaid
Steve Ellner dissects Gabriel Hetland’s simplistic critique of Maduro's government, calling it a one-sided take that ignores key facts. Hetland downplays the brutal impact of U.S. sanctions, like the blocking of bond negotiations and the Petro’s swift blacklisting, and misrepresents the government’s relationship with grassroots power. Ellner points to the 'Year of the Communes' and Ángel Prado’s appointment as proof of ongoing support for popular democracy.
🔗 Read the full opinion piece here: https://venezuelanalysis.com/opinion/neoliberal-and-authoritarian-a-simplistic-analysis-of-the-maduro-government-that-leaves-much-unsaid
#Communes#NicolasMaduro#Sanctions
Chris Gilbert tells the story of El Maizal's communards as they think about how to reactivate the commune's economy.
Read more in Gilbert's latest article, 'The Dream of a Thing: Refounding the Economy of a Venezuelan Commune': https://shorturl.at/CJxDt
#communes#economy
🎙 Episode 30 of the VA Podcast is live!
The latest VA podcast episode dives into the recent Congress on Communal Democracy, exploring its history, participants, and mission to build grassroots alternatives to “liberal democracy.”
Host José Luis Granados Ceja, fellow VA member Cira Pascual Marquina, and Catalan activist Isa Chacón discuss the limits of current political systems, the power of collective self-determination and autonomy, and examples of communal governance in Venezuela and elsewhere. Closing with a call for global solidarity, the Congress’ manifesto champions anti-imperialism, radical social transformation, and a new path beyond the status quo.
Watch the full episode: https://youtu.be/dLwPvyDjXb8
#communes#democracy
📝 INTERVIEW | Juan Lenzo: ‘We Need to Integrate the Communal Economy to Face the Capitalist Maelstrom’
Juan Lenzo, a Venezuelan activist, takes stock of the Communard Union’s current strengths and challenges, with a particular focus on consolidating the communal economy.
Today, 117 communes are part of the Union. To strengthen economic planning, the organization is mapping grassroots productive activity and identifying opportunities to rebuild the communal economy after years of crisis.
One of its flagship efforts is the “Patria Grande del Sur” project in Bolívar state: a 187,000-hectare initiative developed with Brazil’s MST and local campesino communities. The goal is to build a communal agroecological system in phases, from infrastructure to production and education. “We’re not trying to strengthen the old state, we’re building a communal one,” he said.
🔗 Read the full interview here: https://shorturl.at/wejdV
#CommunardUnion#Communes
🎙🔊 PODCAST | The latest Venezuelanalysis episode discusses the role of communes in socialist construction and anti-imperialist struggles.
Communes foster communal exchange over commodities and address racial and patriarchal oppression. Their impact, however, depends on integration into a broader anti-imperialist strategy in the global fight against imperialism, states guest Chris Gilbert.
👉 Watch the full episode here: https://www.youtube.com/watch?v=u0RyfxgQgfc&t=2s
#Communes#Socialism
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
📰 NEWS | Venezuelans Pick State-Funded Projects to Address Local Community Needs
Millions of Venezuelans took part on March 8 in the first National Popular Consultation of 2026, a participatory mechanism allowing organized communities to select and manage publicly funded projects.
Voting took place across 5,336 communal circuits, where residents aged 15 and older chose among proposals previously discussed in local assemblies. Projects focused on priorities such as water distribution, electrical grid repairs, infrastructure works, healthcare equipment, food production, and cooking gas cylinder replacement.
Once approved by majority vote, each project receives US$10,000 in state funding, transferred directly to the community for self-managed execution.
Read our full report here 👉🏾https://shorturl.at/4jxUm
#Communes#NationalPopularConsultation
📸 IN IMAGES | ‘Concrete Results That Benefit Communities’: Venezuelans Pick State-Funded Projects
Organized Venezuelan communities participated in the second National Popular Consultation of 2025, selecting projects for funding. With over 5,300 voting circuits, voters prioritized infrastructure and service initiatives, such as walkway repairs and improvements to the water supply.
Each winning project will receive the equivalent of $10,000, with communal organizations responsible for executing the projects and rendering accounts.
🔗 Don’t miss the full gallery here 👉🏼https://shorturl.at/51gtt
#Communes#NationalPopularConsultation