Можно ли в 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
Sheep can feel emotions like fear, anger, boredom, and happiness. They evaluate their surroundings using checks like suddenness, familiarity, predictability, and control, similar to humans. Sudden events can cause fear, while predictable environments may lead to boredom.
🐑⚽️
@googlefactss
#AnimalWelfare#Sheep#Emotions#AnimalCare#Nature
🇳🇴 NORWAY PHASES OUT UNNATURALLY FAST-GROWING “FRANKEN-CHICKENS”
Norway has announced a gradual phase-out of so-called “franken-chickens” by 2027.
Norway, where about 70 million chickens are raised annually for food production, has become the first country to commit to raising 100% of its poultry under conditions that ensure high animal welfare standards. Animal rights advocates have welcomed the decision, calling it a “historic moment.”
“Franken-chickens,” often referred to in Norway as “turbo-chickens,” are fast-growing birds bred through selective breeding to reach maximum weight in the shortest possible time. Due to rapid growth and extreme size, these chickens suffer from numerous health problems, and most animal welfare organizations strongly condemn this practice.
According to Humane World for Animals, franken-chickens reach their “slaughter weight” in just six weeks, leading to severe strain on their bones, muscles, and ligaments. Their bodies often begin to break down as they grow, and many birds lose the ability to move. Humane League UK describes their lives as “extremely short and painful.”
The animal protection coalition Anima International has been campaigning for five years to eliminate fast-growing chicken breeds in Norway. Several animal welfare groups are also calling for similar measures in the United Kingdom.
Experts emphasize that this decision marks a significant step forward in improving animal welfare.
#AnimalRights#Norway#AnimalWelfare#PoultryFarming#ProtectAnimals
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube
#ForBritain policy: Fully investigate #BadgerCulling with the aim of bringing it to an end.
#AnimalWelfare#BadgerCull#BanBadgerCulling
Full manifesto here: https://www.forbritain.uk/manifesto/
🐾 WEBINAR ALERT: Rabies Elimination and Animal Welfare 🐾
Join us for a focused, hard-hitting session featuring leading voices in veterinary medicine, public health, and youth advocacy. Our expert panel will break down the most pressing issues, from emergency shelter response to global rabies elimination strategies.
📅Date: Feb 19
⏰Time: 2:30 L.T
📍Platform: t.me/aau_ohc
🎤MEET THE PANELISTS:
🔹 Dr. Mesfin Semu Wodajo
Graduate of Moscow Veterinary Academy (1994) and Utrecht University (2000). Former Associate Researcher at Tetracore, LLC. 14 years as Chief of Staff at Banfield Pet Hospital. Currently Medical Director & Owner at Upper Marlboro Veterinary Hospital.
🔹 Dr. Alazar Ayele
Veterinarian specializing in mobile pet care. Co-founder of Beyond Student for Change initiative. Operates a mobile veterinary clinic to expand access to professional animal healthcare and leads community-based stray dog mass rabies vaccination campaigns.
🔹 Dr. Biruk Eshetu
University of Gondar graduate (2015 E.C.). Former founder & president of One Health Innovation Club and VP of Clinical Medicine Club at UoG. Currently Manager of the Animal Welfare and Protection Trauma Shelter, Addis Ababa, where he works extensively with pets and shelter animals.
🔹 Yared Ermiyas
DVM Candidate, Co-founder of AAU One Health Club, and Animal Welfare Advocate.
🎙️Format:Live
📲 Set a reminder and join us!
👇 Drop a "👋" in the comments if you'll be there!
#RabiesElimination#AnimalWelfare#OneHealth#YouthAdvocacy#Webinar#VeterinaryMedicine#ShelterAndRescue
#DairyIndustry#AnimalWelfare#Cattle#AnimalWelfarePolicy#Reformthedairyindustry#UKDairy#Milk#Dairy#ForBritain
Our FULL manifesto can be found here: https://www.forbritain.uk/manifesto/
The UK government has unveiled an unprecedented plan to gradually eliminate animal testing in medical and pharmaceutical research.
The first phase will begin at the end of 2026 and will eliminate tests on mice used to develop treatments for skin and eye irritations.
Additionally, the country has committed to reducing the use of dogs and primates in laboratories by 35% by 2030, fulfilling an election promise made by the Labour Party.
Backed by £60 million, the strategy aims to promote ethical and technologically advanced alternatives that replace animal models without compromising the safety of vaccines, medicines, or pesticides.
Although animal experiments peaked in 2015 — with over 4 million animals used — advances in alternative methods had already helped reduce that number.
However, progress has stalled in recent years, so this new initiative seeks to accelerate the full replacement of animals.
Science Secretary Patrick Vallance stated, “Nobody wants to witness animal suffering,” and the new roadmap will allow governments, companies, scientists, and animal welfare organizations to collaborate on faster and more effective solutions.
Part of the investment will go to a specialized center that will integrate technology, data, and expertise to accelerate the transition to animal-free science.
🐾 Do you think Uzbekistan should implement a similar plan to reduce and replace animal testing? 🇺🇿💭
#AnimalWelfare#AnimalFreeScience#UK#AnimalTesting#ScientificInnovation#LabAnimals#ADNMascotas#AnimalNews#AnimalProtection#OneHealth☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.
Vitalik Buterin Donates to Thai Zoo
Ethereum co-founder Vitalik Buterin donates 10 million Thai baht (~$292,230) to Khao Kheow Zoo, Thailand. The donation, in two installments, starts December 26, 2024. Buterin and family will be adopted by the zoo. Details: Khao Kheow Zoo Announcement
#VitalikButerin#Ethereum#KhaoKheowZoo#Donation#Crypto#Blockchain#Thailand#AnimalWelfare#Charity#Adoption#Philanthropy#Zoo#MOODENG#CommunitySupport#TechForGood#EthereumCoFounder#News