Можно ли в 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
Why I don't have any power?
I guess you have
Okk, what kind? Can I breath in water?
NO
Will I live forever?
NO
Strength or speed?
NO
Okay, then you tell me please
You've the power of HOPE
It will never let you die , just don't let it die
No matter how many times you lost your battle You'll stand again and try, just don't let it die
You'll be able to see light in the dark
Your little little steps will reach to your mark
The road could be long but won't be wrong
All you need to listen is the voices of your heart
We gave you something, which no GOD has
This makes you different, a human from the ash
All the suffering i know you can cope
I believe you child, use the power of HOPE
#review#poetry#hope
NOTHINGNOTHING
There is so much to see, so much to feel.
So much to talk, so much to do.
So much to take, so much to give.
So much to make, so much to break.
So much of so much that makes time scarce.
And then there is nothing.
Nothing that withholds all the nothings that makes everything.
Nothing that subsumes everything we'll ever be.
Nothing that consumes everything as it sees.
#Hope... #poem#review
JUST ANOTHER LIE...
Ever since I started walking he was always next to me. I have known him forever. I loved him forever. He was my best friend before even knowing what friendship was.
Whenever he held me tight I never wanted to let him go.
When others made me cry, he was the only person who made me smile.
There were so many times I wanted to tell him how I felt. I never knew what to say, just like today.
Standing in here embellished my face with a smile. All eyes on us made me feel overwhelmed.
Holding up the glass and all I could think of. What should I say?
Should I say how much I love him?
Should I say I will always love him and he is the love of my life?
Should I say how I really feel?
Or just another lie.
All these years I waited to see love in his eyes. And there it is, for a fraction of second I saw that love in his eyes gazed around just to see the love of his life.
Finally he looked at me raising his glass.
The time has come.
Now what do I say?
That I loved him the most?
That earth stops spinning when he looks at me every time.
Or just another lie.
Well among all the thought that was running in my head all my mouth could comprehend was just another lie.
A congratulatory toss on his wedding day.
#review#shortstory#Hope...
I used to often dwell in the past - achievements and failures, happiness and sadness, joy and anger.
But now I realize that there's nothing much to gain from the past anymore.
Now,
I'm starting to love the dreams of the future, better than the history of the past.
#afterthoughts#inspiration#hope#motivation
@quietworld🍃
Hope meaning in my word's "Light"
We just walking under the tunnel because we know we can find a light end of this tunnel. Life is equal to tunnel so don't stop. Keep walking.
#review#RC#hope
#grammar
#wish
#hope
@fluencyinenglish
@ieltsstrategies
How should I use "I hope" and "I wish"?
@fluencyinenglish
@ieltsstrategies
✅If you want to use "I hope" and "I wish" correctly, you just need to memorize these two phrases:
I hope I can...
I wish I could...
You may be wondering: why do English speakers use the present tense for "hope" and the past tense for "wish"?
The secret is that "could" is not really past tense. It looks like past tense, but it's secretly something different. It's the "unreal" aspect. In other words, it expresses something that's not really true, or not very likely.
We use "wish" to talk about things that are impossible, or things that probably won't happen:
I wish I could fly.
I wish there were more hours in the day.
I wish I'd studied something a little more practical.
On the other hand, we use "I hope..." when there's a good chance that something might happen. You can use it to say what you want to happen in the future:
I hope this cake turns out OK.
I hope we can still be friends.
The grammar of "wish" and "hope"
Here's how "wish" and "hope" look in present, past, and future.
@fluencyinenglish
@ieltsstrategies
❇️Present
I hope this is the last mistake.
I wish my phone worked here.
@fluencyinenglish
@ieltsstrategies
❇️Past
I hope Antonio got home safely.*
I wish you'd told me sooner.
* You can't use "hope" to talk about something in the past, unless you don't know what happened yet. In this example, you haven't heard whther Antonio got home safely.
@fluencyinenglish
@ieltsstrategies
❇️Future
I hope it stops raining soon.*
I wish it would stop raining.
* You follow "hope" with the present tense of a verb, even when you're talking about the future. So you say "I hope it stops" instead of "I hope it will stop."
@fluencyinenglish
@ieltsstrategies
This year, scientists found a way to control HIV without daily medicine. They used special lab-made antibodies in two tests. Some people stayed healthy without HIV drugs long after the treatment stopped. This shows it might be possible to live with HIV without taking pills every day.
💉🦠
[Source]
@googlefactss#HIV#Science#Health#Hope
At this tragic moment our thoughts go both to the people affected by the anguish and fear of having to face war scenarios, and to those who unfortunately are already experiencing it.
TMONK as #charity project It was born to #help others, to give #help in difficult times, to bring #hope where it is very difficult to see it.
But we must also act with facts, not always the word is enough, and for this $TMONK will open a #fundraising for #war victims
We hope that @tonchain, @telegram and all our partner will support this initiative.
For the #freedom e #dignity of people.
To give them a ray of #hope
CHARITY WALLET: UQBj5EpW8M2qYDeb4Sx5XV4XaBGgC0LGGpyV6cwCkvpZiN25 (only $TON)