TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в 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

Hashtags

Резултати

Пронајдени 7 слични објави

Пребарај: #communardunion

当前筛选 #communardunion清除筛选
Venezuelanalysis

@venanalysis · Post #2018 · 01.07.2025 г., 20:24

📝 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

Venezuelanalysis

@venanalysis · Post #1468 · 05.02.2024 г., 16:58

The Communard Union has deployed its “Argelia Laya Brigade” across the country in a bid to strengthen the organization and links between popular power collectives. Beginning on February 4, the activists are divided into "exploratory" and "permanent" brigades, with the former spending two weeks in specific territories and the latter committing to a six-month presence in priority areas as identified by the Communard Union. Their primary objective is to assess political, social, and economic conditions within the visited communes, aiming to formulate work plans that enhance organizational structures and integrate them into the Communard Union. Click here to see the gallery 👉🏽https://venezuelanalysis.com/images/venezuela-communard-union-launches-territorial-brigades/ #Venezuela#CommunardUnion#Communes

Venezuelanalysis

@venanalysis · Post #1587 · 29.05.2024 г., 22:11

🎙 Episode 25 of the Venezuelanalysis Podcast is now available! Venezuela’s revolutionary leader Hugo Chávez defined the commune as the “unit cell” for the construction of socialism. But the road ahead is full of challenges, even more so in a context of imperialist sanctions. In this episode, host José Luis Granados Ceja is joined by fellow VA member Cira Pascual Marquina and by Communard Union communications coordinator Juan Lenzo to discuss the present struggle to strengthen the communal economy and uphold the socialist horizon. Click here to listen to the full episode 👉🏼https://shorturl.at/gf26s #communardunion#communes#vapodcast

Venezuelanalysis

@venanalysis · Post #1935 · 12.04.2025 г., 00:29

📝 INTERVIEW | Communal Feminism in Venezuela: A Conversation with Moira Blanco Cardona The “communal feminism” project emerged from the experiences of women building popular power at the local level. “Communal feminism is the legacy of women who carried gas cylinders, distributed food, and recovered ancestral knowledge,” states Moira Blanco Cardona of the Communard Union. 🔗 Read more in the latest VA interview here: https://venezuelanalysis.com/interviews/communal-feminism-in-venezuela-a-conversation-with-moira-blanco-cardona #CommunalFeminism#CommunardUnion

Venezuelanalysis

@venanalysis · Post #1922 · 31.03.2025 г., 15:31

📸 IN IMAGES | Venezuela: 1,600 Women Discuss ‘Communal Feminism’ at First National Gathering On March 29, more than 1,600 women took part in the Communard Union’s first national gathering on communal feminism in Caracas. The meeting set four key priorities: developing a feminist economy, strengthening healthcare, eliminating gender-based violence, and expanding political participation. A commission was appointed to oversee these initiatives, with annual follow-up meetings planned. 🔗 Don’t miss the full gallery here 👉🏼https://venezuelanalysis.com/images/venezuela-1600-women-discuss-communal-feminism-at-first-national-gathering/ #CommunardUnion#Communes#Feminism

Venezuelanalysis

@venanalysis · Post #2138 · 13.10.2025 г., 19:25

📸 IN IMAGES | Venezuela: Communards Gather to Make ‘Communal Feminism’ a Priority From October 4 to 6, dozens of women representing around 20 communes gathered in Miranda state for a communal feminism meeting organized by the Communard Union and the Ministry of Communes’ School for the Strengthening of Popular Power (EFPP). The gathering addressed the collectivization of care work, feminist economy, political participation, and the prevention of gender-based violence. Organizers agreed to replicate the experience across different regions. 🔗 Don’t miss the full gallery here 👉🏼https://shorturl.at/s4WUS #CommunalFeminism#CommunardUnion#Communes

Venezuelanalysis

@venanalysis · Post #2083 · 01.09.2025 г., 18:13

📰 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