Можно ли в 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
API dan foydalanish
Odatiy hayotimizda ko'plab dasturlardan foydalanamiz, xususan ijtimoiy tarmoqlar(facebook, telegram, instagram...)dan. Sizningcha ushbu ma'lumotlar foydalanuvchi oynasiga qanday qilib tezkorlik bilan uzatiladi? Buning javobi oddiy. Bir dastur bilan ikkinchi dastur o'rtasida muloqotni yaxshilash va aniq tartiblangan holatda uzatish API orqali amalga oshiriladi.
👉Batafsil
👨🏫 Mentor: Xondamir Abduxoshimov
#csharp#api#basic#dotnet
.NET Uzbekistan Community
__________
Telegram | Instagram | Youtube
List
Qishloqdan kelganlar list nimaligini uncha tushunmaydi, o'zi list ham shu qo'yxonaga o'xshagan narsa (Xojiboy Tojiboyev) 😂
List - elementlarni va obyektlarni saqlashga moslashgan to'plam. Bu to'plamga List deb nom berilishiga sabab, ro'yxatlar bilan qulay ishlash mumkin (tarjimasidan bilib olsa bo'ladi). Ro'yxatda nima qilishimiz mumkin, elementlarni ixtiyoriy joyga qo'shish yoki ixtiyoriy joyidan o'chirib tashlash va tartiblash (sort) funksiyasi borligi bilan boshqa to'plamlardan ajralib turadi.
👉Batafsil
👨🏫 Mentor: Tolibjonov Abdulloh
#csharp#collection#list#basic
.NET Uzbekistan Community
______
Telegram | Instagram | Youtube
MVC nima?
MVC bu - Model (Model) View (Ko'rinish) Controller (Kontroller) so'zlarning bosh harflari qisqartmasidan olingan bo'lib Architectural design pattern (Arxitekturaviy dizayn paterni) hisoblanadi.
👉Batafsil
👨🏫 Mentor: Temur G'aniyev
#csharp#mvc#basic#dotnet
.NET Uzbekistan Community
__________
Telegram | Instagram | Youtube
Обновление 22 августа - 28 августа
Коммерция
#коммерция#технология#армирование#моделирование_кр
Опубликована новая инструкция Моделирование выпусков автостоянки сквозным неразрезным армированием
Инструкция описывает технологию моделирования выпусков автостоянки из фундаментной плиты, которые продолжаются неразрезным армированием в вышестоящих вертикальных конструкциях (пилонах или колоннах).
#коммерция#технология#lib-файлы
Опубликована новая инструкция Подготовка lib-файла к работе
❗️Обязательна к ознакомлению!
Инструкция описывает шаги, которые должен выполнить проектировщик для подготовки lib-файла перед использованием его в проекте.
#коммерция#fm#семейства_кр
Разработаны семейства к альбому технических решений КЖ2.1
Со списком семейств можно ознакомиться по ссылке.
The Inhuman World of Ours:
Millions of Pregnant Women Without the Basic Care
A global shortage of nearly a million midwives is leaving pregnant women without the basic care needed to prevent harm, including the deaths of mothers and babies, according to new research.
Almost half the shortage was in Africa, where nine in 10 women lived in a country without enough midwives, the researchers said.
Anna af Ugglas, chief executive of the International Confederation of Midwives (ICM) and one of the study’s authors, said:
“Nearly 1 million missing midwives means health systems are stretched beyond capacity, midwives are overworked and underpaid, and care becomes rushed and fragmented.
“Intervention rates rise, and women are more likely to experience poor-quality care or mistreatment,” she said.
“This is not only a workforce issue, it is a quality and safety issue for women and babies.”
For all women to receive safe, good-quality care before, during and after pregnancy, an additional 980,000 midwives would be needed across 181 countries, the study found.
According to previous research, universal access to midwife-delivered care could prevent two-thirds of maternal and newborn deaths and stillbirths, saving 4.3 million lives annually by 2035.
The ICM said the issue was not only a lack of training places for midwives, but also a failure in many countries to employ trained midwives where they were needed and to retain those who were working in health services.
Prof Jacqueline Dunkley-Bent, ICM’s chief midwife and another of the report’s authors, said:
“In many settings, midwives are educated but not absorbed into the workforce or not enabled to practise fully, compounding this already serious and universal shortage of midwives, and still leaving women without access to the care that midwives are trained to provide.”
More than 90% of the global midwife shortage was in low- and middle-income countries.
Africa has only 40% of the midwives it needs, the eastern Mediterranean only 31%, and the Americas just 15%, researchers found. Shortfalls were much smaller, although still present, in other regions including south-east Asia and Europe.
The study, published in the journal Women and Birth, estimated the number of midwives who would be needed to carry out a list of basic midwifery tasks for all eligible women and babies in 181 countries.
The tasks included counselling on contraception, antenatal care and screening, and care during childbirth.
Although midwife numbers were increasing, the gap between what was needed and the available workforce looked likely to “persist well into the next decade”, the researchers said – beyond the 2030 deadline set by global sustainable development.
#millions#pregnant#women#basic#care
📱American Оbserver - Stay up to date on all important events
🇺🇸
Not Guide Navigation
Our goal is to make the process of learning web3 understandable, interactive, and beneficial for everyone. We've collected all the necessary guides and instructions in one place.
Current campaigns:
⁃ Basics of web3
⁃ NFTs. Pictures worth millions
⁃ Everything about the TON blockchain
⁃ How to buy cryptocurrency
Hashtags:
⁃ #basic / #intern / #advanced
⁃ #earnings
⁃ #update
Reflect, doubt, explore.
💎