Можно ли в 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
Several countries to import wheat from India after ban on shipment lifted
The agriculture ministry has projected a record 120 MT of wheat output in 2025-2026 crop years (July-June), trade sources said that output is definitely higher than 117 MT in 2024-25 crop year.
The area under wheat this season has increased to 33.41 million hectares (mha), 3% higher than last year, exceeding the normal sown area of 31.2 mha
#Agriculture
https://t.co/uvwNj9BuM7
Job Title: Poultry production manager
Job Type: On-site - Permanent (Full-time)
Job Sector:#Agriculture
Work Location: Gondar, Ethiopia
Experience Level: Senior
Vacancies: 1
Salary/Compensation: Monthly
Deadline: 8/11/2023
Description:
We are looking for a skilled poultry production manager who has at least a Bsc in animal science and related field. The applicant needs to have a minimum 6 years of experience. The location is Weleta.
__________________
Purpose Black Eth Trading s.c
[Verified Company ✅]
128 Jobs Posted
From: @freelance_ethio | @freelanceethbot
For our Amharic Channel, Join @afriworkamharic
🌎 The guano islands of Peru once fueled global agriculture. Thick layers of seabird droppings here created natural fertilizer so valuable, nations fought for control in the 19th century. ✨
#history⚡#ecology⚡#agriculture
👉subscribe Interesting Planet
#Koulouba | 06 mai 2025 | #Agriculture
15e Session du CSA : Priorité à la souveraineté alimentaire et au développement rural
Sous la présidence du Général Assimi GOÏTA, la 15e session du Conseil Supérieur de l’Agriculture (CSA)s’est tenue le 6 mai 2025 à Koulouba, réunissant le Premier ministre, des ministres clés et des représentants agricoles.
À l’ordre du jour :
- Bilan 2024 (inondations, insécurité)
- Exécution des recommandations précédentes
- Perspectives 2025-2027
🔷️Performances 2024 :
- 11M+ tonnes de céréales
- 640 000 tonnes de coton
- 97 000 tonnes de viande
- 113 000 tonnes de poisson
🔷️Mesures annoncées:
- Subventions :
- Coton (300 FCFA/kg)
- Engrais minéraux (14 000 FCFA/sac)
- Semences de maïs (1 500 FCFA/kg)
- Soutien à la mécanisation, pisciculture et crédit agricole
🔷️Objectif : Renforcer l’autosuffisance alimentaire et les chaînes de valeur locales.
🌎 Vertical farming—growing crops in stacked indoor layers—uses up to 95% less water than traditional agriculture, while reducing pesticide use and transportation emissions. Some modern vertical farms employ LED lighting and hydroponics, completely soil-free, to produce lettuce and herbs year-round in urban settings. ✨
#ecology⚡#technology⚡#agriculture
👉subscribe Interesting Planet
👉more Channels
🌎 The future of Earth’s ecology could be transformed by vertical farming—multistory indoor farms that use LED lighting and hydroponics to grow crops year-round. These farms use up to 95% less water than traditional agriculture and can be built in cities, reducing transport emissions and land use. ✨
#ecology⚡#technology⚡#agriculture
👉subscribe Interesting Planet
👉more Channels
🌎 The Amazon basin is home to “terra preta” soils—dark, fertile earth created by ancient humans mixing charcoal, bones, and compost. This enriched soil still boosts crop yields centuries later, showing early Amazon cultures mastered sustainable farming. ✨
#Amazon⚡#archaeology⚡#agriculture
👉subscribe Interesting Planet
News: #Ethiopia earns $288.48 million from horticulture exports in seven months, amid sector bottlenecks
Ethiopia has generated $288.48 million from the export of more than 160,000 tons of #horticultural products during the first seven months of the current Ethiopian fiscal year, the Ministry of #Agriculture announced, despite concerns raised by stakeholders over infrastructure gaps, logistics constraints, and land supply management.
The ministry disclosed the performance following a consultative meeting with relevant public institutions and local and foreign investors engaged in the horticulture sector to assess progress over the reporting period.
Minister of Agriculture Addisu noted that horticulture, alongside coffee, remains one of Ethiopia’s priority export commodities, highlighting its strategic importance in boosting foreign exchange earnings.
Ethiopia’s horticulture industry has faced mounting challenges in recent years, largely driven by security...
Read more: https://addisstandard.com/?p=55463
📹 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