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

Резултати

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

Пребарај: #snowy

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

@PensivePost · Post #5840 · 29.06.2022 г., 21:19

Why am i so addled, i seek retort through this creation. Can't understand a thing, anymore. I just need Salvation What am i gonna gain, if anything, why do i need revelation. I do just fine without mass, getting back to isolation? Why is it so important, why look for identification? Is it the curiosity or the fear of seperation? There is inspiration, there is recreation, there is manipulation, sensation, violation & frustration but is there anything that's necessary? Is there any elevation? I know it bothers none but please, tell me, where am i heading to, what is my destination? #Snowy#review

Pensive|

@PensivePost · Post #5602 · 12.01.2022 г., 18:22

I mutilate myself, no matter what i do. Acting all spirit, i maim when I'm disregarded, when I'm passed over. Acting all foul isn't my cup of tea either, i maim again, i incapacitate either way. Being ignoble and or moral, both roads are noxious to me. What do i fancy then? You blemish me, your bygones. I can't condone it. I can't strand you either. You, your, it impedes me, candidly but won't gash you by disclaim, renounce.... Won't? Well, can't is more apt, can't bestow to soar your agony.... But about my torment? I have nowhere to go, no door left open, I'm stuck, stuck with you. I'll dwell, I'll persist, that's what I've been doing, that's what i can keep up with. No possibility, either at whim or reluctantly, i have to adhere, no recourse.... I'd be thrusting here, i don't know the stretch, the extent, maybe perpetuity. #review#Snowy

Pensive|

@PensivePost · Post #5589 · 07.01.2022 г., 12:05

Why am i so addled, i seek retort through this creation. Can't understand a thing, anymore. I just need Salvation What am i gonna gain, if anything, why do i need revelation. I do just fine without mass, getting back to isolation? Why is it so important, why look for identification? Is it the curiosity or the fear of seperation? There is inspiration, there is recreation, there is manipulation, sensation, violation & frustration but is there anything that's necessary? Is there any elevation? I know it bothers none but please, tell me, where am i heading to, what is my destination? #Snowy#review

Pensive|

@PensivePost · Post #5570 · 29.12.2021 г., 04:59

You were fire, i wasn't ice I was supposed to but it wasn't nice I was magma that was piquant Why was our bond so highly turbulent? The violent gesticulation of air around your flames Wasn't any good for my fever but i got used to the games We were bonded the way we weren't meant to be Was it destiny, i wondered or was it our will that was the key You're no good for me, i know, said she But it was too late for her to be set in the world again like a bird, free If we're meant to do it together, yes my love, we suffer like the way we suffered You'd be the flame of my candle that demolishes my wax, he uttered Afterall, diamonds dice diamonds, they are suited together Shouldn't be befuddled with types different but stay where they belong, forever #Snowy #review