Можно ли в 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
We all are one.
The sun, the moon and the earth are one (once),
But in the time they all seperated,
Being and living far away,
But they all are one.
We born on different places,
We raised in different cities,
We studied in different institutions,
But we all are on one stage. i.e,, Life.
Our handwriting may be different
But the alphabet are one,
Pens may be different,
But the ink is same,
Books may be different,
But the knowledge is eternal.
We all are separated ,
by life,
by paths,
By careers,
But our hearts are together,
and We all are one.
Our tastes,
our preferences,
our perspectives,
our thinking,
May be different but,
We all are one.
S NAVEEN
#poetry#SN#review
Seperation lives
The life of human started from seperation,
Separation from the ocean,
Separation from the species, and
Separation from the womb of mother.
Nature is separated,
Oceans are separated,
Continents are separated, and so,
The nations emerged seperately.
Separation is the birth of new life,
Separation leads to innovation,
Separation is the worse, but
Separation is the nature.
When two persons seperates,
The heart brokes, and
Mind resides in despair, and
Life teaches the valuable lessons.
Even the origin of universe,
Started from the separation,
From one to one and another,
Separation is an unending process.
Separation begins with despair and,
End with hope.
Separation is natural and,
Separation is permanent.
PS: ignore grammatical mistakes
S NAVEEN
10-07-2022
#poetry#SN#review
Deadly hunger
I have seen that one person begged,
Other person insulted his fellow being,
And the other person cried for his condition.
I have seen people selling their body,
I have seen one died, and
Other inviting the death.
I have seen one in misery,
Other fighting to end the misery,
And other mentally broke down in it.
I have seen the starvation of children,
I have seen men working hard, and
The old seeking for help.
I have seen false promises of politicians,
Flop ideas of business men,
Which told to end hunger and poverty.
Hunger, a six letters word,
Running the world with ruthless,
Where it has no permanent end.
S NAVEEN
23-06-2022
#poetry#SN#review
These nights
I hope sleep find its way,
Before my thoughts destroy me,
Exhausted feelings and emotions will make,
These nights more scary.
There was a nights in moon light,
where we are sleeping peacefully,
Why this artificial lights making,
These nights more terrible.
In the war of mind and heart,
Sleep is just a pawn,
Where heart and mind will never win the war,but
These nights witness as spectators.
S NAVEEN
#poetry#SN#review
Sky...
You are the blue,
You are the light,
You are the carrier of clouds.
You have been witnessing the war,
You have been witnessing the peace,
You have been witnessing the love,
You have been witnessing the world. (From Alpha)
You have seen the tragedy,
You have seen the lives,
You have seen the nature,
You are the meaning of eternal.
You took the poison,
You took the pollution,
Yet, you never changed your colour. (like politicians)
You are the miniature of the oceans.
You are the floating blue ocean and
wonder of the universe.
S NAVEEN
#poetry#SN#review
On Long distance relationship.
Distance is just a word,
When two hearts beat together,
Kilometres and miles are just measurements,
When two souls turns into one.
There may be lack of communication,
But two minds will think the same.
Distance and lack of communication is;
Just for those, who thinks they are separate,
Not for those, who thinks they are together.
Love never thinks it way in impossibilities,
It always find it ways in possibilities.
S. NAVEEN
#poetry#SN#review
Eternal Love
I just opened the eyes,
Aloud tears filled the room,
That's the first time that,
I saw true form of love,
My Mother.
She hugged and kissed me,
With happiness and tears in her eyes,
That's the selfless love.
I have never seen 'her' before,
But I felt her touch in womb,
Her hands touched me,
Her womb protected me.
I have seen her and cried,
Her gentleness in heart,
Her intangible love,
Is the pinnacle in the whole world.
S NAVEEN
#poetry#SN#review