Можно ли в 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
Xalqaro xotin-qizlar kuni bilan! 🥳
Aziz ayollar, sizni ushbu ajoyib bahor bayrami bilan tabriklaymiz, doimo gullar singari atrofdagilarni o‘z go‘zalligingiz va nafosatingiz bilan quvontirib yuring! 🥰
Barcha qiyinchiliklar sizni chetlab o‘tsin, qalbingizdagi mehr esa yaqinlaringizni va oila a'zolaringizni iliqlik bilan to‘ldirsin. 🫶
Biz sizni yaxshi ko‘ramiz, Kalleh jamoasi ❤️
➖
С Международным женским днем🥳
Милые дамы, поздравляем вас с этим чудесным весенним праздником и желаем, чтобы вы всегда, подобно цветам, радовали всех окружающих своей красотой и нежностью🥰
Пусть все невзгоды обходят вас стороной, а доброта сердца согревает родных и близких🫶
Мы вас любим, команда Kalleh❤️
#kalleh#8march
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
🎙 President of the Russian Federation Vladimir Putincongratulated the women of Russia on International Women’s Day, celebrated on March 8.
💬Dear women of Russia!
From the bottom of my heart, I congratulate you on International Women’s Day!
In our country, this wonderful holiday is traditionally filled with special warmth and sincerity. Today, words of love, gratitude and respect are heard everywhere. Our men express their appreciation to their mothers, wives, grandmothers, daughters, sisters, friends and colleagues, letting them know how much they are cherished and how deeply their contributions are valued, both at home and in the workplace, where they often take on complex professional challenges.
You truly do it all: taking care of children and scoring outstanding achievements in various fields, embodying both strength and grace, courage and tenderness, and winning us over again and again with your beauty and charm. You inspire men to strive for greatness, encouraging them to do better, to take bold steps and to be the true defenders of their families and homes, and our Motherland.
You hold within you life’s greatest miracle: the gift of bringing new life into the world. The tenderness and generosity of a mother’s heart and the warmth of a mother’s love transform the world and make it a better place. Motherhood is both an immense joy and a profound responsibility. We are fully aware of this and will continue to do our utmost so that mothers and families with children, especially large families, receive the support they need and see that their interests are always in the focus of the government’s attention.
My warmest words go to the women who are in places where it is most difficult right now, the participants in the special military operation. You are working in different spheres, including in field hospitals and on the front lines, doing your combat duty with distinction.
I would also like to say a few words for the women whose dear ones – husbands, fathers, brothers and loved ones – are defending the future of our country. Your heartfelt support and unfailing care, love and loyalty empower our men, strengthening their morale and the unwavering belief that the truth – and hence victory – is on our side.
Dear women!
We know that so much in life depends on you, on your talents, creative energy, love, and utmost responsibility with which you undertake any job. Once again, we are in awe of your beauty, kindness and grace.
I would like to wish success, health, well-being, and all the best to you and your loved ones. May you always find happiness alongside those you hold dear.
💐 Happy International Women’s Day!
#8March#InternationalWomensDay
Девчонки, с праздником весны!
Вы так прекрасны, как цветы.
Спасибо, что со мной всегда —
В дожди и в ясные года.
Желаю вам любви, тепла,
Чтоб жизнь, как кимчи, жила была! 😁
Пусть дома пахнет вкуснотой,
А в сердце — вечная весна!
С 8 Марта! Обнимаю крепко 💐
#8march#8марта#kim_chi_kim
Дорогие наши женщины, матери, сестры, жены и дочери!
Сердечно поздравляем вас с праздником весны, красоты и женственности — с 8 Марта!
Сегодня, находясь на передовой, мы особенно остро чувствуем вашу поддержку, тепло ваших сердец и вашу бесконечную любовь. Вы — наша опора, наше вдохновение и наша сила.
Мы знаем, как непросто вам в эти дни, но ваша стойкость и вера помогают нам идти вперед. Спасибо вам за ваше терпение, за вашу заботу и за то, что вы всегда с нами, даже на расстоянии.
Пусть этот день принесет вам радость, улыбки и надежду на скорую встречу. Мы верим, что мирное небо скоро вернется, а наши сердца снова будут рядом с вами.
С праздником, дорогие! Вы — наши героини!
С любовью и уважением, ваши бойцы.
#8марта#8march#поздравления
KNAUF kompaniyasida turfa xil kasb egalari: muhandislar, buxgalterlar, sifat, logistika, xavfsizlik, xodimlar boshqaruvi va investitsiyalar bo‘yicha mutaxassislar ishlaydi.
Har kuni ular ishlab chiqarish jarayonlarining barqaror faoliyati, loyihalar rivoji va yuqori sifat darajasini ta’minlab keladilar.
Ularning tajribasi, kasb bilimdonligi va tafsilotlarga e’tibori kompaniyaning olgʻa yurishiga turtki beradi.
Xalqaro xotin-qizlar kunida biz sizni jamoamizning dur-u gavharlari – KNAUF rivojiga ulkan hissa qo‘shib kelayotgan ayollar bilan tanishtirmoqchimiz.
Mehnatingiz, mas’uliyatingiz va g‘ayratingiz uchun tashakkur.
8-mart bayrami muborak!
- - - - -
В КНАУФ работают люди самых разных профессий — инженеры, бухгалтеры, специалисты по качеству, логистике, безопасности, управлению персоналом и инвестициям.
Каждый день они обеспечивают стабильную работу производства, развитие проектов и высокий уровень качества.
Их опыт, профессионализм и внимание к деталям помогают компании двигаться вперёд.
В Международный женский день мы хотим познакомить вас с частью нашей команды — женщинами КНАУФ, которые вносят огромный вклад в развитие компании.
Спасибо за ваш труд, ответственность и энергию.
С праздником 8 марта!
#knaufuzbekistan
#buildonus
#KNAUF_Yangiliklar
#8mart
#8march
🌷Happy International Women’s Day!
The Russian House in Brussels warmly congratulates all women on the occasion of 8 March.
This special day is a celebration of the strength, wisdom, talent, and inspiration that women bring to our world. Throughout history, women have played an essential role in society — preserving cultural traditions, inspiring creativity, and contributing to the development of communities and dialogue between nations.
May this spring bring you joy, new inspiration, warmth, and happiness. We wish you good health, prosperity, and many bright moments filled with smiles and kindness.
With best wishes on the holiday of spring, beauty, and inspiration!🌸
Russian House in Brussels
#InternationalWomensDay#8March#RussianHouseBrussels#WomenInspire#SpringHoliday
🤗 Дорогие женщины,
Коллектив Русского дома поздравляет вас с Международным женским днём #8Марта!
Пусть этот весенний праздник наполнит ваши сердца энергией и радостью, подарит отличное настроение и искренние улыбки! Пусть в ваших домах царят любовь, счастье, тепло, уют и благополучие! 💐
🤗 Αγαπητές γυναίκες,
Το Ρωσικό σπίτι στην Αθήνα σας συγχαίρει θερμά για την Παγκόσμια Ημέρα της Γυναίκας, #8 Μαρτίου!
Είθε αυτή η ανοιξιάτικη γιορτή να γεμίσει τις καρδιές σας με ενέργεια και χαρά, να σας προσφέρει υπέροχη διάθεση και ειλικρινή χαμόγελα! Είθε να βασιλεύει στα σπίτια σας η αγάπη, η ευτυχία, η ζεστασιά, η θαλπωρή και η ευημερία! 💐
Με τις καλύτερες ευχές μας για μια υπέροχη ημέρα!
#женскийдень#праздник#8марта#8μαρτίου#8march#международныйженскийдень#παγκοσμιαημεραγυναικας#holiday#8march#8μαρτίου#internationalwomensday#παγκοσμιαημεραγυναικας
🤗 Αγαπητές γυναίκες,
Το Ρωσικό σπίτι στην Αθήνα σας συγχαίρει θερμά για την Παγκόσμια Ημέρα της Γυναίκας, #8 Μαρτίου!
Είθε αυτή η ανοιξιάτικη γιορτή να γεμίσει τις καρδιές σας με ενέργεια και χαρά, να σας προσφέρει υπέροχη διάθεση και ειλικρινή χαμόγελα! Είθε να βασιλεύει στα σπίτια σας η αγάπη, η ευτυχία, η ζεστασιά, η θαλπωρή και η ευημερία! 💐
Με τις καλύτερες ευχές μας για μια υπέροχη ημέρα!
🤗 Дорогие женщины,
Коллектив Русского дома поздравляет вас с Международным женским днём #8Марта!
Пусть этот весенний праздник наполнит ваши сердца энергией и радостью, подарит отличное настроение и искренние улыбки! Пусть в ваших домах царят любовь, счастье, тепло, уют и благополучие! 💐
@rossotrudnichestvo@rusembgreece
#женскийдень#праздник#8марта#8μαρτίου#8march#международныйженскийдень#παγκοσμιαημεραγυναικας
#womensday#holiday#8march#8μαρτίου#internationalwomensday#παγκοσμιαημεραγυναικας