Можно ли в 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
Continuous practice of standard #IPC is key to preventing the spread of infection from patients to health workers, health workers to other health workers or their families, and from the patients to the rest of the community.
🔗Guideline:
https://ncdc.gov.ng/themes/common/docs/protocols/111_1579986179.pdf
Infection Prevention and Control (IPC) is an essential aspect of the clinical management of #LassaFever.
Healthcare workers are urged to always practice standard #IPC measures when attending to patients.
🔗Download, read and share our guidelines:
https://www.ncdc.gov.ng/themes/common/docs/protocols/92_1547068532.pdf
As Nigeria continues the fight against Lassa fever, our healthcare workers remain our strongest line of defence.
The Nigeria Centre for Disease Control and Prevention reminds all health professionals to stay alert, every fever case matters.
Standard precautions save lives:
🧼 Clean your hands before and after contact.
🩺 Use the right PPE based on risk.
🧹 Keep your environment clean.
🗑 Dispose of waste safely.
For detailed guidance, read the full Lassa Fever Advisory for Healthcare Workers here:
https://ncdc.gov.ng/themes/common/docs/protocols/373_1771241608.pdf
Protect yourself. Protect your colleagues. Protect your patients.
Infection prevention isn’t optional, it saves lives.
#LassaFever#IPC#NCDCNigeria
📃
"Despite high mortality & morbidity, drug-resistant bacterial infections remain the forgotten pandemic"
In this PLOS Biology article, our #IPC/#AMR coordinator Dr Tochi Okwor & colleagues write on the need for urgent action & investment focusing on this 'pandemic'.
Read and share:
https://journals.plos.org/plosbiology/article?id=10.1371/journal.pbio.3001903
Improving the quality and safety of health care through informed #IPC practices such as #HandHygiene bolsters the feeling of protection by patients & healthcare workers.
Facility managers should ensure #handhygiene at every point of care is promoted at all times.
Health workers,
Continuous and appropriate use of infection prevention and control methods is crucial to protect yourself from Healthcare-Associated Infections and further spread in the community.
🔗Download our National Guideline on #IPC for #VHF
https://ncdc.gov.ng/themes/common/docs/protocols/111_1579986179.pdf
Standard #IPC is key to preventing the spread of infection from patients to health workers, health workers to other health workers or their families, and from the patients to the rest of the community.
🔗Download our National Guideline on #IPC for #VHF
https://ncdc.gov.ng/themes/common/docs/protocols/111_1579986179.pdf
Health workers,
Continuous and appropriate use of infection prevention and control methods is crucial to protect yourself from Healthcare-Associated Infections and further spread in the community.
🔗Download our National Guideline on #IPC for #VHF
https://ncdc.gov.ng/themes/common/docs/protocols/111_1579986179.pdf
Famine threat spreads in #Sudan’s Darfur as hospital attack kills 22 amid ongoing war
Famine is threatening additional areas in war-ravaged Sudan’s western #Darfur region, a global hunger monitoring body warned on Thursday, even as an attack by paramilitary forces on a military hospital in the country’s south killed at least 22 people, including the hospital’s director and three medical staff.
Sudan has been engulfed in conflict since April 2023, following a power struggle between the Sudanese military and the paramilitary Rapid Support Forces (#RSF). The war has triggered what the United Nations has described as the world’s worst humanitarian crisis
The Integrated Food Security Phase Classification (#IPC) said acute malnutrition has reached famine-level thresholds in two more towns in Darfur — Umm Baru and Kernoi in North Darfur province — though it stopped short of formally declaring famine due to lack of sufficient data on mortality and.....
https://www.daijiworld.com/news/newsDisplay?newsID=1305714
The overall goal of Infection Prevention & Control is to maintain an environment of care that minimises risks of infection for patients, staff & visitors.
These #IPC guidelines must be practised by all #HCWs in public and private primary, secondary & tertiary healthcare facilities.
Read more in the Nigerian Manual of Infection Prevention and Control:
https://ncdc.gov.ng/themes/common/docs/protocols/296_1649340294.pdf
The overall goal of Infection Prevention & Control is to maintain an environment of care that minimises risks of infection for patients, staff & visitors.
These #IPC guidelines must be practised by all #HCWs in public and private primary, secondary & tertiary healthcare facilities.
Read more in the Nigerian Manual of Infection Prevention and Control:
https://ncdc.gov.ng/themes/common/docs/protocols/296_1649340294.pdf
One-third of #Somalis to face hunger in March: #UN officials
Some 6.5 million people, or about a third of Somalia's population, will face crisis levels of hunger through March, an increase of 1.7 million since January, UN officials warned.
Speaking to reporters on Wednesday at the UN headquarters via video link, World Food Programme (#WFP) Director of Emergency Preparedness and Response Ross Smith said the latest Integrated Food Security Phase Classification (#IPC) report for Somalia, released on Tuesday, confirmed fears that the humanitarian situation in Somalia has significantly worsened.
"Of these, two million of the most vulnerable women and children are expected to face severe hunger," with over 1.8 million children under the age of 5 to face acute malnutrition in 2026, he said.
Smith said Somalia is in the midst of a very complex hunger crisis, where two rainy seasons have failed, conflict and insecurity....
https://menafn.com/1110791078/One-Third-Of-Somalis-To-Face-Hunger-In-March-UN-Officials