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

Резултати

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

Пребарај: #peasants

当前筛选 #peasants清除筛选
Venezuelanalysis

@venanalysis · Post #2011 · 23.06.2025 г., 18:46

📰 NEWS | Campesino Movements Demand Venezuelan Gov’t Step In to Protect Activists from ‘Criminalization’ Attacks Venezuelan campesino movements have denounced the arrest of Lilibeth Rangel in Zulia and the detention of 28 rural producers in Barinas as part of a broader pattern of criminalization. The Small Farmers Movement (MPA) is urging government institutions to intervene and address judicial delays and alleged landowner interference in security operations. Campesino families from La Rubiera and La Fortuna estates have been demanding land titles under the 2001 Land Law for years. 🔗 Read the full report here: https://venezuelanalysis.com/news/campesino-movements-demand-venezuelan-govt-step-in-to-protect-activists-from-criminalization-attacks/ #Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #1754 · 25.09.2024 г., 14:44

On September 21, Venezuelan campesino leader Iraidez Andrade was killed by masked hitmen in Barinas state. He had been a prominent voice in the Las Mercedes land struggle and was working with local communities to secure land for campesino families. Rural organizations have called for justice and an end to impunity for the ongoing violence against campesino leaders. Full report here 👉🏼https://shorturl.at/dzgzG #Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #2302 · 11.03.2026 г., 14:38

📹 VIDEO | Rice Producers Protest Agribusiness Pressure in Venezuela Rice producers across Venezuela are taking to the streets ahead of the upcoming harvest, warning that prices offered by agroindustrial firms could leave many farmers unable to cover production costs. Campesino groups say large conglomerates are using their control over silos, imports, and distribution to push prices down, while limited access to credit keeps farmers dependent on company financing. After talks with producers, Agriculture Minister Julio León Heredia announced a provisional price. But campesino organizations warn they were barely represented in negotiations. Click here to read our full report 👉🏾https://venezuelanalysis.com/news/venezuela-rice-producers-denounce-agribusiness-pressure-demand-govt-support-for-fair-prices/ #Agriculture#Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #2285 · 25.02.2026 г., 23:06

📰 NEWS | Venezuela: Rice Producers Denounce Agribusiness Pressure, Demand Gov’t Support for Fair Prices Venezuelan rice producers have staged demonstrations in Barinas, Cojedes, Guárico and Portuguesa, demanding state action to secure fair prices for their crops. According to producer representative Víctor Martínez, agribusiness firms are offering $0.32–0.38 per kilo ahead of harvest, compared to $0.50–0.55 last year. Producers have set a $0.70 per kilo target in negotiations, citing rising input costs and lack of credit access. Growers also report financing agreements in which companies provide inputs and collect up to 60% of the crop as payment. Campesino organizations are considering a rally in Caracas. Government officials have not yet commented. Read the full report here 👉🏾https://venezuelanalysis.com/news/venezuela-rice-producers-denounce-agribusiness-pressure-demand-govt-support-for-fair-prices/ #Agriculture#Peasants#Campesinos

Venezuelanalysis

@venanalysis · Post #2075 · 25.08.2025 г., 21:40

📰 NEWS | Venezuela: Turkish Investors to Take Over State-Owned Sugar Mills Under ‘Strategic Alliances’ Venezuela has signed agreements with Turkish investors to manage three state-owned sugar mills — Central Venezuela (Zulia state), Santa Clara (Yaracuy state), and Ezequiel Zamora (Barinas state) — as part of new 'strategic alliances,' Agriculture Minister Julio León announced. Authorities have not disclosed further details. Previous experiences with similar alliances in the countryside have raised concerns among campesinos regarding transparency and impacts on small-scale producers. 🔗 Read the full report here: https://shorturl.at/pwPmt #Peasants#Campesinos#PrivateSector#Sugar

Venezuelanalysis

@venanalysis · Post #1997 · 05.06.2025 г., 19:39

🖊 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