TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в 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

Hashtags

Резултати

Пронајдени 3 слични објави

Пребарај: #vlv

当前筛选 #vlv清除筛选
Pensive|

@PensivePost · Post #5221 · 24.05.2021 г., 12:21

The ring of love#1 How far it is? Where are we leading to? What are we? Why we cry? Why we become happy? These thoughts been running in my mind while I am watching the waves on the sea shore. The pleasant music of the waves diverted me from those unanswered questions. The cool breeze touched my hot skin and I just shivered for a moment and smiled with a pleasant face. Through this long journey human race struggled a lot to be here what we are now is a long way journey that the human race has come to. Everyone are different in their own aspects of life. If a man/women is rough, then he might have faced more in his/her life and that's why he/she looks rough and tough to handle. And in other hand if a man or a women is cool and soft, then it means they had built their life in a completely different manner. Everyone has their own way of sculpting their own life. Every one has to face both types of characters in their life and should learn to face all these people. We can't use any filters and neglect them. Because it is a real life where only unexpected things happens. But we dream many things we expect many things in our life and we have the freedom to do so. No one could tell us not to dream and making it true is not in our hand. This doesn't meant that we should not dream we have to dream to move on in our life, so don't stop dreaming... "There can't....." "Hey Aashiv come here man see what we found" a voice interrupted my conversation with my "inner me". I turned towards her and waved my hands and signalled them that I am coming. I got up from the sand and ran towards them. My team found some oldest ring while excavating inside the sand. The ring looked gorgeous and I ran towards the sea and washed the ring with the water. And I just observed something written on the ring it said "Samuthra kumaari", which means "The Princess of Ocean". Suddenly a fictional character came to my mind which I studied in the novel called "Ponniyin selvan". With the sudden reminder of that character I put that ring in my pocket and ran from that place. I reached my bike and I went to kushi beach which is situated near Rameswaram. I consider that place as my soulful site and whenever I feel low I will go to that sea shore and stay there until I feel good. I went there and sat there for a moment and cried hard. I don't know why I am crying like this. But I cried without any thoughts and after a moment everything in my mind settled and I became clear enough to think deep in to my past. A name suddenly came to my mind and I spelled "Riya". Suddenly a single drop of tear came out of my left eye and it fell on the sand. It's been ten years... I didn't even spell her name. When I saw the name in the ring, the dark side of my mind came out and it took me to the darkest part of my life. With this I fainted in the sand and I heard the sound of my friends saying "Aashiv get up man what happened to you?" When I opened my eyes I was going in the car with my "Riya". And... To be continued... Dm me to know more about Aahsiv #review#share#VLV

Pensive|

@PensivePost · Post #5202 · 13.05.2021 г., 12:05

Lost her in the dark sky I lost her in the dark sky, Thought she is hiding behind the stars, It costs my life to find her, I risked my lifetime to search her, Weeks and years passed by, Can't able to find her. At the beginning, I thought, I lost her in the dark sky, But she is purposefully hiding, She knows where I am but I don't Even after knowing this I searched, I didn't stop even after becoming mad. A past reminded me a conversation Her words, "What will you do if you lost me?" I replied I will become mad Those words haunted me deep. Those true words proves my loyalty But more of the past reminded me, My bag full of mistakes... My fate cursed me more and said you deserve it for what you did to her.... #review #poetry #share #VLV

Pensive|

@PensivePost · Post #5203 · 13.05.2021 г., 12:12

Still haunting... Somewhere in the edge of my destiny, I lost myself in the world of memories.. Somewhere in the zenith of the mountain I disappeared in the mist of snow.. Somewhere in the darkest part of my life, I have been left to suffer alone.... #review #share #poet #VLV